Python String Methods


Method Description
capitalize() Converts the first character of the string to the upper case and remaining string to the lower case.
center() Returns the centered string adding fill character to right and left.
count() Count of number of occurrences of a substring.
endswith() Checks if a string ends with specified character(s).
expandtabs() Expands the tabs(\t) with a specified number of spaces.
find() Finds specific character(s) from a string.
index() Index location of a substring from the string.
isdigit() Checks if the variable contains only digits.
islower() To check if the specified string is in lower case or not.
isnumeric() If the string is numeric or not.
isspace() Checks if the string is just a white space(s).
istitle() Checks if the string is a title or not.
isupper() Checks if the specified string is in upper case or not.
join() Joins each character of the string with the new string.
length() Finds the length of characters in the string.
lower() To convert all characters of the string to the lower case.
lstrip() To remove the left white spaces from the string.
replace() To replace character(s) from the string with a new character(s).
rstrip() To remove the right white spaces from the string.
split() Split the string based on the separator.
startswith() To check if string starts with specified character(s).
strip() To remove white spaces from both sides of the string.
swapcase() Swaps the lower case character to upper and upper case to lower.
title() The first character of each word is converted to upper case.
upper() To convert all characters of the string to the upper case.

Python String capitalize() Method

The Python string capitalize() method returns a string by converting the first character to the upper case and the remaining string to the lower case.

Note: Observe in the example below, the only first character is converted to upper case and if there is any other upper case character, it is converted into lower case.

In [1]:
text = 'how arE you? What are you doing today?'
text.capitalize()
Out[1]:
'How are you? what are you doing today?'

Python String center() Method

It will create the string with a specified width and will fill the gap with the fill character. The original string will be placed at the center.

The default fill character is space, but we can use any custom fill character.

Default space as fillchar

In [1]:
text = 'Tim'
text.center(10)
Out[1]:
'   Tim    '

‘a’ as fillchar

In [2]:
text = 'Tim'
text.center(10, 'a')
Out[2]:
'aaaTimaaaa'

Python String count() Method

Returns the count of occurrences of a substring from the string. It has an optional start and end index to search within that specified range. The default value of the start index is 0 and the end index is the end of the string.

Note: Here, the end index means up to the index position. The character in that position is not included.

In [1]:
text = 'How are you? What are you doing?'
text.count('are')
Out[1]:
2

With start and end index. Now the number of occurrences is only 1.

In [2]:
text = 'How are you? What are you doing?'
text.count('are',0,7)
Out[2]:
1

When character(s) is not available in the string.

In [3]:
text = 'How are you? What are you doing?'
text.count('to')
Out[3]:
0

Python String endswith() Method

To check if a string ends with the specified character(s). Returns ‘True’ if the string ends with the character(s), else ‘False’. It has an optional start and end index to search within that specified range. The default value of the start index is 0 and the end index is the end of the string.

Note: Here, the end index means up to the index position. The character in that position is not included.

In [1]:
name = 'Will Smith'
name.endswith('g')
Out[1]:
False
In [2]:
name = 'Will Smith'
name.endswith('h')
Out[2]:
True

With Start and End index.

In [3]:
name = 'Will Smith'
name.endswith('h',0,6)
Out[3]:
False
In [4]:
name = 'Will Smith'
name.endswith('S',0,6)
Out[4]:
True

Python String expandtabs() Method

It expands the tabs with a specified number of spaces. The number of spaces (tab size) parameter is an optional argument, with a default value of 8.

Print without expandtabs.

In [1]:
text = 'Hey,\thow are you?'
print(text)
Hey,	how are you?

expandtabs() with default tabsize.

In [2]:
text = 'Hey,\thow are you?'
print(text.expandtabs())
Hey,    how are you?

tabsize 16.

In [3]:
text = 'Hey,\thow are you?'
print(text.expandtabs(16))
Hey,            how are you?

Python String find() Method

To find a specific substring from a string. It will return the index position if a substring is found, else returns -1. It has an optional start and end index to search within that specified range. The default value of the start index is 0 and the end index is the end of the string.

Note: Here, the end index means up to the index position. The character in that position is not included.

In [1]:
text = 'how are you?'
text.find('a')
Out[1]:
4
In [2]:
text.find('are')
Out[2]:
4

When character is not there in the string, then it will return -1.

In [3]:
text.find('q')
Out[3]:
-1

With start and end index.

In [4]:
text.find('are',0,3)
Out[4]:
-1
In [5]:
text.find('are',4,7)
Out[5]:
4

Python String index() Method

Returns the index position of the substring from the string. If the substring is not found, it returns an error. It has an optional start and end index to search within that specified range. The default value of the start index is 0 and the end index is the end of the string.

Note: Here, the end index means up to the index position. The character at the end position is not included.

In [1]:
text = 'how are you?'
text.index('are')
Out[1]:
4

When substring not found.

In [2]:
text.index('not')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-50b88ffd6ec8> in <module>()
----> 1 text.index('not')

ValueError: substring not found

With start and end index.

In [3]:
text.index('are',3,7)
Out[3]:
4

With start and end index, substring not found.

In [4]:
text.index('are',0,4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-bcca0c2116c7> in <module>()
----> 1 text.index('are',0,4)

ValueError: substring not found

Python String isdigit() Method

To check if the variable contains only digits. Returns True if the variable contains only digits, else False.

In [1]:
name = 'Will Smith'
name.isdigit()
Out[1]:
False
In [2]:
number = '450'
number.isdigit()
Out[2]:
True

Python String islower() Method

To check whether the specified string is in lowercase or not. Returns True if it is lowercase, else False.

In [1]:
name = 'WILL SMITH'
name.islower()
Out[1]:
False
In [2]:
name = 'will smith'
name.islower()
Out[2]:
True

Python String isnumeric() Method

If the string is numeric or not. Returns True if it is numeric, else False.

In [1]:
number = '125'
number.isnumeric()
Out[1]:
True
In [2]:
number = '125d'
number.isnumeric()
Out[2]:
False

Python String isspace() Method

Checks if the string is just a whitespace(s). Returns True if the string is only whitespace(s), else False.

In [1]:
name = '    '
name.isspace()
Out[1]:
True
In [2]:
name = '     will smith'
name.isspace()
Out[2]:
False

Python String istitle() Method

Checks if the string is a title or not. Returns True if it is a title, else False.

In [1]:
name = 'The Hero'
name.istitle()
Out[1]:
True
In [2]:
name = 'Will smith'
name.istitle()
Out[2]:
False

Python String isupper() Method

Checks if the specified string is in upper case or not. Returns True if it is upper case, else False.

In [1]:
name = 'WILL SMITH'
name.isupper()
Out[1]:
True
In [2]:
name = 'will smith'
name.isupper()
Out[2]:
False

Python String join() Method

Joins each character of the string with the new string.

In [1]:
text = 'how are you?'
("ABC").join(text)
Out[1]:
'hABCoABCwABC ABCaABCrABCeABC ABCyABCoABCuABC?'

Python String length() Method

Finds the length of characters in the string, including whitespace.

In [1]:
text = 'Hello! Peter Cruise'
len(text)
Out[1]:
19

Python String lower() Method

To convert all characters of the string to lowercase.

In [1]:
name = 'Peter Cruise'
name.lower()
Out[1]:
'peter cruise'

Python String lstrip() Method

To remove the left whitespace(s) from the string. By default, it will remove whitespace(s), but we can pass a left substring that we want to trim.

By default it will trim whitespaces.

In [1]:
text = '    how are you?   '
text.lstrip()
Out[1]:
'how are you?   '

Trimming a substring ‘how’

In [2]:
text = 'how are you?   '
text.lstrip('how')
Out[2]:
' are you?   '

It compares each character of the substring with the string and if it is found then remove it.

In [3]:
text = 'howh are you?   '
text.lstrip('Hhellowa ')
Out[3]:
're you?   '

Python String replace() Method

To replace a character(s) from the string with a new character(s). Actually, it does not replace the specific character(s) in the string, instead returns the new string because the string is immutable.

In [1]:
text = 'Hey, how ade you?'
text.replace('d','r')
Out[1]:
'Hey, how are you?'
In [2]:
text = 'Hey, how are you?'
text.replace('Hey','Hello')
Out[2]:
'Hello, how are you?'

Passing the count as 2, will replace only the first 2 occurrences of ‘Hello’.

In [3]:
text = 'Hello, Hello, Hello.'
text.replace('Hello','Hey',2)
Out[3]:
'Hey, Hey, Hello.'

Python String rstrip() Method

Remove the right whitespace(s) from the string. By default, it will strip the whitespace(s), but we can pass the substring to trim.

In [1]:
text = '    how are you?   '
text.rstrip()
Out[1]:
'    how are you?'
In [2]:
text = '    how are you?'
text.rstrip('you?')
Out[2]:
'    how are '

Python String split() Method

It will try to split the string based on the separator. By default, space(”) is the separator and the separator is removed from the string.

We also have another parameter for maxsplit, i.e. the maximum number of splits we want to make. For example, if we wish to split a string into two strings, then we can specify maxsplits as 1.

In [1]:
text = 'Hello! Peter Cruise'
text.split()
Out[1]:
['Hello!', 'Peter', 'Cruise']
In [2]:
#we want to split based on '!'
text.split('!')
Out[2]:
['Hello', ' Peter Cruise']
In [3]:
text.split('e',1)
Out[3]:
['H', 'llo! Peter Cruise']

Python String startswith() Method

To check if a string starts with a specified character(s). Returns True if the string starts with a specified character(s), else False.

In [1]:
name = 'Will Smith'
name.startswith('w')
Out[1]:
False
In [2]:
name = 'Will Smith'
name.startswith('W')
Out[2]:
True

Python String strip() Method

Remove whitespace(s) from both sides of the string. We can pass the substring as an argument, and it will compare each character of the substring with each character of the string and remove it.

In [1]:
text = '    how are you?   '
text
Out[1]:
'    how are you?   '
In [2]:
text.strip()
Out[2]:
'how are you?'

It can strip the characters in the substring from the sting. Comparing character by character, not whole substring at once.

In [3]:
text = 'Hey, how are you?'
text.strip('Hesd?you, ')
Out[3]:
'how ar'

Python String swapcase() Method

Swaps the lowercase character to upper and uppercase to lower.

In [1]:
text = 'how are you?'
text.swapcase()
Out[1]:
'HOW ARE YOU?'
In [2]:
text = 'How are you?'
text.swapcase()
Out[2]:
'hOW ARE YOU?'

Python String title() Method

The first character of each word is converted to upper case. If any of the remaining characters are upper case, they would be converted to lower case.

In [1]:
text = 'how arE you?'
text.title()
Out[1]:
'How Are You?'

Python String upper() Method

To convert all characters of the string to uppercase.

In [1]:
name = 'Peter Cruise'
name.upper()
Out[1]:
'PETER CRUISE'

Video

https://youtu.be/qK-v9b2B4tI