There are so many built-in methods for strings in Python. With these methods, you can easily or conveniently manipulate strings.
In this post, you will learn the different built-in methods for strings and how to use them for manipulating strings in Python.
capitalize() method
This method is used to change the first letter in a string to upper case if the character is an alphabet. However, if the first character is not an alphabet, nothing changes in the string.
print('hello'.capitalize()) print('1hello'.capitalize()) #output #Hello #1hello
upper() method
This method converts all the alphabets in a given string to upper cases.
S = 'steve'.upper() print(S) S = 'hello how are you?'.upper() print(S) S = '12hello'.upper() print(S) #outputs #STEVE #HELLO HOW ARE YOU? #12HELLO
lower() method
The lower() method converts all the alphabets in a string to lower cases.
S = 'HELLO'.lower() print(S) S = '123HellO'.lower() print(S) #outputs #hello #123hello
swapcase() method
The swapcase() changes the alphabet in lower cases to upper cases and those in upper cases to lower cases.
S = 'HELLO world'.swapcase() print(S) #output #hello WORLD
title() method
The title() method capitalizes all the first characters in a string that are alphabets.
S = 'hello how are you?'.title() print(S) S = '25units of eggs?'.title() print(S) #outputs #Hello How Are You? #25Units Of Eggs?
casefold() method
This method converts a string into lowercase. This is particularly useful or suitable in making caseless comparisons between strings.
S = 'YELLOW' print(S.casefold()) S = 'yellow' print(S.casefold()) S = '5 Yellow Cups' print(S.casefold()) #output #yellow #yellow #5 yellow cups
count() method
The count() method is used to determine the number of a specific character or group of characters in a string.
S = 'hello world' print(S.count('h')) print(S.count('ll')) print(S.count('o')) #output #1 #1 #2
index() method
This method returns the index of the first occurrence of a given substring. If the substring is not found, it will throw a value error indicating that the substring is not found.
print('hello'.index('h')) print('hello'.index('o')) print('hello'.index('ll')) print('hello'.index('j')) #outputs #0 #4 #2 #Traceback (most recent call last): #File "/Users/ex.py", line 4, in <module> #print('hello'.index('j')) #ValueError: substring not found
find() method
This method determines whether a given substring exists in a string. If it exists, it will return the index of the substring, else it will return -1. It behaves almost like the index() method, except that it doesn’t throw an error if the substring doesn’t exist in the string.
S = 'hello' print(S.find('l')) print(S.find('e')) print(S.find('z')) #output #2 #1 #-1
You can also find or replace substrings using regular expressions in Python.
rfind() method
This returns the index of the first occurrence of a given substring of a string from the right end of it. However, it returns -1 if the substring does not exist in the string.
S = 'apple' print(S.rfind('p')) print(S.find('p')) print(S.rfind('j')) #outputs #2 #1 #-1
rindex() method
This method behaves like the rfind, except that it throws an error if the substring provided does not exist in the string. The rindex returns the index of the first occurrence of a given substring of a string from the right end of it.
S = 'apple' print(S.rindex('p')) print(S.rindex('a')) print(S.rindex('j')) #outputs #2 #0 #Traceback (most recent call last): #File "/Users/ex.py", line 5, in <module> #print(S.rindex('j')) #ValueError: substring not found
replace() method
This method finds and replaces all the appearances of a given substring in a string with another substring.
S = 'hello' print(S.replace('l', 'k')) #output #hekko
isalnum() method
This method returns True if all the characters in a string are alphanumerical, else returns False.
S = 'hello' print(S.isalnum()) S = '1hello' print(S.isalnum()) S = '*1hello' print(S.isalnum()) #output #True #True #False
isalpha() method
If the string is composed of only the letters of the alphabet, this method returns True. However, it returns False, if one or more of the characters in the string is not an alphabet.
S = 'hello' print(S.isalpha()) S = 'hello1' print(S.isalpha()) #outputs #True #False
isascii() method
This method determines whether all the characters in a string are encoded in UTF-8 or ASCII. It returns True if they are UTF-8 characters and False if otherwise.
S1 = 'huj;er0e' print(S1.isascii()) S2 = 'hello'.encode('utf-32') #encoding the string to utf-32 print(S2.isascii()) #outputs #True #False
isdecimal() method
The Isdecimal() method returns True if all the characters in a string are decimal numbers and False if one or more of the characters are not decimal numbers.
S = '12345' print(S.isdecimal()) S = '0005' print(S.isdecimal()) S = '23J' print(S.isdecimal()) S = '22.5' print(S.isdecimal()) #outputs #True #True #False #False
isdigit() method
This method returns True if all the characters in the string are digits (0-9), else returns False.
S = '12345' print(S.isdigit()) S = '5a' print(S.isdigit()) S = '120' print(S.isdigit()) S = '0100' print(S.isdigit()) S = '1.5' print(S.isdigit()) #output #True #False #True #True #False
isidentifier() method
The Isidentifier() method is used to determine whether a string is a valid identifier name in Python. It returns True if the string is a valid identifier and returns False if it is not.
print('hello'.isidentifier()) print('1hello'.isidentifier()) print('__hello'.isidentifier()) print('#hello'.isidentifier()) #output #True #False #True #False
isnumeric() method
To determine whether a string represents a number, the method isnumeric returns True if the string represents a number and False when it does not.
print('123'.isnumeric()) #True print('0123'.isnumeric()) #True
isprintable() method
This method returns True if all the characters in a string are printable and False if otherwise.
print('hello'.isprintable()) print('hello\t'.isprintable()) #output #True #False
isspace() method
This is used to determine if all the characters in a string are whitespaces. This method returns True if they are white spaces and False, if otherwise.
S =' ' print(S.isspace()) S = ' hello ' print(S.isspace()) S = ' \t\n ' print(S.isspace()) #output #True #False #True
islower() method
This method is used to determine whether all the characters in a string are in lower cases. It returns True if all the characters are in lower cases, but False if one or more characters are not.
S = 'hello' print(S.islower()) S = 'Hello' print(S.islower()) S = 'hello222' print(S.islower()) #output #True #False #True
istitle() method
This method returns True if the words in the string are in title cases and returns False if they are not.
S = 'Hello World' print(S.istitle()) S = 'Hello world' print(S.istitle()) #outputs #True #False
isupper() method
This method returns True if all the alphabets in the string are in upper cases or capital letters and returns False if one or more of the characters is in lower case.
S = 'HELLO' print(S.isupper()) S = 'Hello' print(S.isupper()) S = 'HELLO123' print(S.isupper()) #outputs #True #False #True
startswith() method
The startswith returns True if a given substring is at the beginning of a string and returns False if otherwise.
S = 'apple' print(S.startswith('a')) S = 'apple' print(S.startswith('ap')) S = 'apple' print(S.startswith('p')) S = 'this is a sentence' print(S.startswith('th')) #outputs #True #True #False #True
endswith() method
Just like the startswith() method, this method returns True if a given substring is at the end of a string and returns False if otherwise.
S = 'apple' print(S.endswith('e')) S = 'apple' print(S.endswith('le')) S = 'apple' print(S.endswith('a')) S = 'this is a sentence' print(S.endswith('sentence')) #outputs #True #True #False #True
join() method
This method inserts a given substring or character in between a string or a sequence. For example:
S = 'hello world' print(('-').join(S)) print(' '.join(S)) print('***'.join(S)) L = ['a', 'b', 'c', 'd'] print('-'.join(L)) #outputs #h-e-l-l-o- -w-o-r-l-d #h e l l o w o r l d #h***e***l***l***o*** ***w***o***r***l***d #a-b-c-d
strip() method
The strip method removes all the trailing white spaces or a given substring from a string.
S = ' hello how are you? ' print(S.strip()) S = 'hello how are you?' print(S.strip('?')) S = '*hello how are you?****' print(S.strip('*')) #outputs #hello how are you? #hello how are you #hello how are you?
lstrip() method
This is used to remove all the trailing white spaces or a given substring on the left-hand side of a string.
S = ' hello how are you? ' print(S.lstrip()) S = 'hello how are you?' print(S.lstrip('?')) S = '*hello how are you?****' print(S.lstrip('*')) #outputs #hello how are you? #hello how are you? #hello how are you?****
rstrip() method
This is used to remove all the trailing white spaces or a given substring on the right-hand side of a string.
S = ' hello how are you? ' print(S.rstrip()) S = 'hello how are you?' print(S.rstrip('?')) S = '*hello how are you?****' print(S.rstrip('*')) #outputs #hello how are you? #hello how are you #*hello how are you?
split() method
This method splits or breaks a string into distinct substrings using a given substring or character as a point for separation. If no separator is provided as an argument, the default separator becomes a white space.
Also, by default, this method splits a string into unlimited parts. However, if you wish to split the string any number of times, then you would have to provide an additional argument for the maximum number of splits.
The split method returns a list of substrings after the split operation.
S = 'abc def ghi' print(S.split()) S = 'abc def ghi' print(S.split(' ')) S = 'apple, orange, pineapple' print(S.split(',')) S = 'abc def ghi jkl mno pqr' print(S.split(' ', 1)) print(S.split(' ', 2)) print(S.split(' ', 3)) print(S.split(' ', 4)) #outputs #['abc', 'def', 'ghi'] #['abc', 'def', 'ghi'] #['apple', ' orange', ' pineapple'] #['abc', 'def ghi jkl mno pqr'] #['abc', 'def', 'ghi jkl mno pqr'] #['abc', 'def', 'ghi', 'jkl mno pqr'] #['abc', 'def', 'ghi', 'jkl', 'mno pqr']
splitlines() method
This method breaks a multi-line string into a list of substrings as shown below:
S = 'This is a multi-line string.\nThis is the second line.\nThis is the third line.' print(S.splitlines()) #output ['This is a multi-line string.', 'This is the second line.', 'This is the third line.']
rsplit() method
Just like the split() method, this method splits or breaks a string into distinct substrings after removing the separator substring and returns a list of the stripped substrings.
It also allows you to provide the number of splits to do and the splitting starts from the right side of the string.
S = 'hello world' print(S.rsplit()) print(S.rsplit('d')) S = 'abc def ghi' print(S.rsplit(' ')) print(S.rsplit(' ', 1)) #outputs #['hello', 'world'] #['hello worl', ''] #['abc', 'def', 'ghi'] #['abc def', 'ghi']
removeprefix() method
This method removes a given substring appearing at the beginning of a string.
S = 'hello' print(S.removeprefix('h')) print(S.removeprefix('he')) S = 'an apple' print(S.removeprefix('an ')) #output #ello #llo #apple
removesuffix() method
This method removes a given substring from a string if it appears at the end of the string.
S = 'hello' print(S.removesuffix('o')) print(S.removesuffix('llo')) S = 'an apple!!!' print(S.removesuffix('!')) #output #hell #he #an apple!!
encode() method
This method is used to return the encoded version of a string in formats such as utf-8, utf-16, latin or even utf-32.
S = 'apple' print(S.encode('utf-8')) print(S.encode('utf-16')) print(S.encode('utf-32')) #outputs #b'apple' #b'\xff\xfea\x00p\x00p\x00l\x00e\x00' #b'\xff\xfe\x00\x00a\x00\x00\x00p\x00\x00\x00p\x00\x00\x00l\x00\x00\x00e\x00\x00\x00'
ljust() method
This method is used to justify a string to the left and add paddings to the right if the length of the string is less than the paddings. The method accepts as an argument the number of paddings and the character to use for padding.
If no character is provided for padding, it pads the string with white spaces.
S = 'hello' print(S.ljust(20)) print(S.ljust(20, '*')) S = 'This is just a very short sentence.' print(S.ljust(20)) #outputs #hello #hello*************** #This is just a very short sentence.
rjust() method
This justifies the string to the right and pads up spaces in the left with white spaces or any substring provided as long as the length of the string is less than the padding. It accepts as an argument the number of paddings and the character to use for padding.
Like the ljust() method, if no character is provided for padding, it pads the string with white spaces.
S = 'hello' print(S.rjust(20)) print(S.rjust(20, '*')) S = 'This is just a very short sentence.' print(S.rjust(20)) #outputs #hello #***************hello #This is just a very short sentence.
center()
This method is used to pad characters equally at the right and left-hand sides of a string if the length of the characters is below the number of characters to be padded.
S = 'hello' print(S.center(20)) print(S.center(20, '*')) S = 'This is just a sentence.' print(S.center(40, '*')) #outputs #hello #*******hello******** #********This is just a sentence.********
zfill() method
This is used to add leading zeros to a numeric string if the length of the string is less than the padding.
S = '123' print(S.zfill(5)) S = '00123' print(S.zfill(5)) print(S.zfill(10)) S = 'hello' print(S.zfill(10)) #outputs #00123 #00123 #0000000123 #00000hello
expandtabs() method
This is used to assign tabs in a string to a given number of white spaces. For example, you might want to assign a tab to mean 2 white spaces and so on.
S = 'hello\tthere' print(S.expandtabs(2)) S = 'hello\t\tthere' print(S.expandtabs(2)) S = 'hello\tthere' print(S.expandtabs(10)) #outputs #hello there #hello there #hello there
partition() method
This method breaks a string into three parts using a separator substring.
This is done at the first occurrence of the separator substring from the left. It divides the string into three parts returning the part before the separator, the separator and the other part.
If the separator is not found in the string, it returns the string and two substrings containing the separator.
S = 'hello world' print(S.partition(' ')) S = 'hello how are you doing' print(S.partition('are')) print(S.partition('abd')) #outputs #('hello', ' ', 'world') #('hello how ', 'are', ' you doing') #('hello how are you doing', '', '')
rpartition() method
This method breaks a string into three parts starting from the right. It searches for the separator substring from the right.
It divides the string into three parts returning the part before the separator, the separator and the other part.
If the separator is not found, it returns a tuple containing two items containing the separator and the string.
S = 'hello there, Adam!' print(S.rpartition(' ')) S = 'hello how are you doing' print(S.rpartition(' ')) print(S.rpartition('abd')) #outputs #('hello', ' ', 'world') #('hello how ', 'are', ' you doing') #('hello how are you doing', '', '') #outputs #('hello there,', ' ', 'Adam!') #('hello how are you', ' ', 'doing') #('', '', 'hello how are you doing')
format() method
This method is primarily used for string substitutions. In order to use this method, empty curly braces or curly braces (optionally with numbers) are placed in places where substitutions are to be performed on a string.
S = 'Hello Mr. {}'.format('Dan') print(S) S = 'Good {0}, how are you {1}'.format('morning', 'today') print(S) S = 'Good {1}, how are you {0}'.format('today', 'morning') print(S) #outputs #Hello Mr. Dan #Good morning, how are you today #Good morning, how are you today
format_map() method
This method is similar to format, except that it takes an argument of a dictionary that maps the substitutions.
To make use of the format_map() method for string substitution, curly braces containing keys in a dictionary are placed in positions where you want to make substitutions as shown below:
abv = {'a':'apple', 'b':'ball', 'c':'cup', 'd':'dog'} S = 'A is for {a}' print(S.format_map(abv)) S = 'B is for {b}' print(S.format_map(abv)) S = 'B is for {c}' print(S.format_map(abv)) #outputs #A is for apple #B is for ball #B is for cup