This blog describes some of the string methods used in python. Strings has richer set of methods which are inherited from string module in earlier version of pythons.
Find method
This method finds a substring within a larger string. It returns index number of the leftmost substring. If not found, it returns -1. Syntax string.find(‘substring’)
Below is the example for finding subtring. It returns the leftmost index number of a substring and returns -1 if the substring is not found
str = '''The wind is blowing.
A flower loses its scent.
Silence is blowing.'''
print(str.find('wind'))
print(str.find('blowing'))
print(str.find('that'))
Output
4
12
-1
Example 2
str = '!!! How are you ****'
print(str.find('!'))
print(str.find('&'))
print(str.find('*'))
Output
0
-1
16
lower method
Returns lower case of a string. Syntax string.lower().
str = '!!! How are you !!!'
print(str.lower())
Output
!!! how are you !!!
Lower Method example
str = input('Please enter y for yes and n for no')
if str.lower() == 'y':
print('You choose yes')
elif str.lower() == 'n':
print('You choose no')
else:
print('You choose nothing')
Output
Please enter y for yes and n for no : Y
You choose yes
Replace method
This method replaces old string with a new string. Syntax string.replace(old_string,new_string)
str = 'The wind is blowing'
print('Actual string : ',str)
print('Replacing is with eez : ',str.replace('is','eez'))
Output
Actual string : The wind is blowing
Replacing is with eez : The wind eez blowing