12 Python Programming
12 Python Programming
SESSION 12
Strings
A string is a sequence of characters enclosed with quotes(single or
double)
Eg. ‘Welcome to CS GE’
0 1 2 3 4 5 6 7 8 9 10
H E L L O W O R L D
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>>S[0]
>>>’H’
Negative Indices
Strings are immutable
Components of a string cannot be altered any attempt to it will lead to
error
Strings can be concatenated using +
operator
>>>’Computer’ +’ Science’
>>>’Computer Science’
>>>’Hi’ +’How’+’are’+’you’
>>>’HiHowareyou’
>>>max(‘AZ’, ‘C’, ‘BD’, ‘BT’)
>>>‘C’
>>>min(‘BD’,’AZ’, ‘C’)
>>>‘AZ’
>>>max(‘hello’,’How’,’Are’,’You’,’sir’)
>>>’sir’
Slicing- retrieving a substring
>>>message =‘HELLP WORLD’
0 1 2 3 4 5 6 7 8 9 10
H E L L O W O R L D
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>>message[0: 5]
>>>’HELLO’
>>>S[-10:-5]
>>>’ELLO ‘
Python also allows to extract a subsequence
of the form
start:end:inc
Membership
◦ We can check membership of individual characters using in operator
◦ The expression would yield a True or a False
>>>’H’ in ‘Hello’
>>>True
>>>’H’ in ‘hello’
>>>False
Built in Functions in Strings
◦ count()- to find the number of occurrences of character in the string
>>>'hello how are are you'.count('o’)
>>>3
S='hello how are are you’
S.count(‘o’) will give 3
find()- returns the index of first occurrence of the substring (if found). If not
found, it returns -1.
E.g.
quote = 'Let it be, let it be, let it be’
result = quote.find('let it’)
print(result)
Answer =11 (its small l in let it)
rfind()-returns the highest index (or rightmost index) of the substring (if found). If not
found, it returns -1.
Eg
quote = 'Let it be, let it be, let it be’
result = quote.rfind('let it’)
Answer -22