Python string methods

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s