String Methods in Python

String Methods in Python

endswith

endswith checks if the a particular string ends with the character passed into the method. It returns True if true and False if not.

>>>sentence = 'The weather is hot'

>>>print(sentence.endswith('hot'))
True

>>>print(sentence.endswith('cold'))
False

startswith

startswith checks if the a particular string starts with the character passed into the method. It returns True if true and False if not.

>>>sentence = 'The weather is hot'
>>>print(sentence.startswith('the'))
False

>>>print(sentence.startswith('The'))
True

find

find returns the position of the string passed into the method if it exist.

>>>sentence = 'The weather is hot'
>>>print(sentence.find('The'))
0
#this means that 'The' starts with position 0 in the string as python starts its indexing from 0 not 1

>>>print(sentence.find('hot'))
15
#this means that 'hot' starts with position 15 in the string as python starts its indexing from 0 not 1

join

join splits the characters and joins each character by the string passed.

>>>sentence = 'The weather is hot'
>>>print(','.join('Hello'))
H,e,l,l,o

upper and lower

upper() returns all characters in UPPER CASE while lower() returns all characters in LOWER CASE

>>>sentence = 'The weather is hot'
>>>print(sentence.upper())
THE WEATHER IS HOT

>>>print(sentence.lower())
the weather is hot

strip

removes whitespaces from left and right

>>>sentence = ' The weather is hot '
>>>print(sentence)
 The weather is hot
>>>print(sentence.strip()) 
The weather is hot

lstrip

removes whitespaces from left

>>>sentence = ' The weather is hot '
>>>print(sentence)
 The weather is hot
>>>print(sentence.lstrip()) 
The weather is hot

rstrip

removes whitespaces from right

>>>sentence = 'The weather is hot '

>>>print(sentence)
The weather is hot  
>>>print(sentence.lstrip()) 
The weather is hot

capitalize

Capitalizes only the first letter in the string.

>>>sentence = 'the weather is hot'
>>>print(sentence.capitalize())
'The weather is hot'

casefold

Returns the string in lower case

>>>sentence = 'the weather is hot'

>>>print(sentence.casefold())
'the weather is hot'

count

counts the number of frequency the character occurs in the string

>>>sentence = 'The weather is hot'
>>>sentence.count('is')
1