Worksheet Exercise On Strings
Worksheet Exercise On Strings
Length of String
python
Copy code
>>> len("Computer Science") # Length of "Computer Science"
# Answer: 16
Given:
python
Copy code
str = "Pithon"
(a) str[-2]
Answer: 'o'
(c) str[10]
Answer: Error (index out of range)
python
Copy code
s = "Python World"
(a) s.index('y')
Answer: 1
(b) s.index('y', 0)
Answer: 1
(a) str1.find('twinkle')
Answer: 0
(b) str1.find('twinkle', 2)
Answer: 8
5. String Comparisons
python
Copy code
S = "python program"
P = "012345"
(a) S[5]
Answer: 'n'
(b) S[5:]
Answer: 'n program'
(c) S[:5]
Answer: 'pytho'
(d) S[0:5]
Answer: 'pytho'
(e) S[::2]
Answer: 'pto rgam'
(f) S[:10:2]
Answer: 'pto r'
(g) S[::-1]
Answer: 'margorp nohtyp'
(h) S[-1:-10:-2]
Answer: 'mropn'
(i) S[8:-3:3]
Answer: 'oa'
(j) S[-3:8:1]
Answer: '' (no output since slicing in the reverse direction with positive step results in an
empty string)
7. Membership Operators
python
Copy code
ch = "Chennai Training Institute for Education"
(a) "chennai" in ch
Answer: False (case-sensitive)
(b) "Ch" in ch
Answer: True
(a)
python
Copy code
S = 'computer'
R = ''
for i in S:
R = R + i
print(S + R)
# Answer: 'computercomputer'
(b)
python
Copy code
S = 'computer'
R = ''
for i in S:
R = i + R
print(S + R)
# Answer: 'computerretupmoc'
(c)
python
Copy code
S = 'computer'
R = '#'
for i in S:
R = R + i
print(S + R)
# Answer: 'computer#computer'
(d)
python
Copy code
S = 'computer'
R = '#'
for i in S:
R = i + R
print(S + R)
# Answer: 'computerretupmoc#'
These answers cover the exercises based on string manipulation, indexing, slicing, and
membership operations as found in the document. Let me know if you'd like further explanations
for any of these!