String Methods in Python
In Python, you can manage strings using various methods. There are quite a few of them.
Why are methods useful? Often, a method can achieve the same result as multiple instructions. Therefore, using methods can reduce the length of your source code and improve its readability.
What are the string methods in Python?
Here's a complete list of all the methods applicable to strings.
capitalize
Returns the string with the first character capitalized and the rest in lowercase.
string_name.capitalize()
Example
name="Andrea MININI"
name.capitalize()
Output
'Andrea minini'
center
Centers the string within a specified width, padding it with spaces on both sides. The second parameter (optional) specifies a fill character instead of spaces.
string_name.center(width [, 'fillchar'])
Example
name="Andrea Minini"
name.center(20, '-')
Output
'---Andrea Minini----'
count
Counts the number of occurrences of a substring within the string. Optional parameters specify the start and end positions for the search.
string_name.count('sub' [, start [, end]])
Example
name="Andrea Minini"
name.count('ni')
Output
2
decode
Decodes the string using the specified codec. If not specified, it uses the default string codec. The error parameter handles exceptions for encoding errors.
string_name.decode([encoding [, error]])
encode
Encodes the string using the specified codec. If not specified, it uses the default string codec. The error parameter handles exceptions for encoding errors.
string_name.encode([encoding [, error]])
endswith
Returns true if the string ends with the specified suffix; otherwise, it returns false. Optional parameters define the start and end positions for the search.
string_name.endswith(suffix [, start [, end]])
Example
name="Andrea Minini"
name.endswith('ni', 1, 5)
Output
False
expandtabs
Replaces tabs in the string with a specified number of spaces. If the tab size parameter is not specified, it defaults to 8 spaces.
string_name.expandtabs(tabsize)
Example
name="Andrea \t Minini"
name.expandtabs(1)
Output
Andrea Minini
find
Searches for a substring within the string. Returns the position of the first occurrence from the left. Returns -1 if not found. Optional parameters define the start and end positions for the search.
string_name.find(sub [, start [, end]])
Example
name="Andrea Minini"
name.find('ni')
Output
9
index
Similar to find, but raises a ValueError if the substring is not found. Optional parameters define the start and end positions for the search.
string_name.index(sub [, start [, end]])
Example
name="Andrea Minini"
name.index('ni')
Output
9
isalnum
Returns true if the string is alphanumeric.
string_name.isalnum()
Example
name="Andrea Minini"
name.isalnum()
Output
false
isalpha
Returns true if the string is alphabetic. Otherwise, it returns false.
string_name.isalpha()
Example
name="Andrea Minini"
name.isalpha()
Output
false
It returns false because the string "Andrea Minini" contains a space (a non-alphabetic character).
isdecimal
Returns true if the string contains only decimal digits ("0123456789"). Otherwise, it returns false.
string_name.isdecimal()
Example
score="30"
score.isdecimal()
Output
true
If the variable has a numeric value (e.g., score=30), the method raises an exception because it's not a string.
isdigit
Returns true if the string contains only digits, including subscript and superscript. Otherwise, it returns false.
string_name.isdigit()
Example
score="302"
score.isdigit()
score.isdecimal()
Output
true
false
Unlike isdecimal, the isdigit method includes more numeric symbols (subscript and superscript).
isnumeric
Returns true if the string contains only numeric characters, including decimal digits, subscript, superscript, fraction symbols, Roman numerals, etc. Otherwise, it returns false.
string_name.isnumeric()
Example
score="30¼"
score.isnumeric()
score.isdigit()
score.isdecimal()
Output
true
false
false
Unlike isdigit, the isnumeric method includes more numeric symbols (e.g., fractions).
islower
Returns true if the string contains only lowercase letters. Otherwise, it returns false.
string_name.islower()
Example
name="Andrea Minini"
name.islower()
Output
false
The method returns false because the string contains two uppercase letters (A and M).
isspace
Returns true if the string contains only spaces. Otherwise, it returns false.
string_name.isspace()
Example
name="Andrea Minini"
name.isspace()
Output
false
The method returns false because the string contains other characters besides spaces.
istitle
Returns true if the string is titlecased (each word starts with an uppercase letter followed by lowercase letters).
string_name.istitle()
Example
name="Andrea Minini"
name.istitle()
Output
true
isupper
Returns true if the string contains only uppercase letters. Otherwise, it returns false.
string_name.isupper()
Example
name="ANDREA MININI"
name.isupper()
Output
true
join
Joins a list of strings into a single string, separated by a specified character or string.
'separator'.join(seq)
Example
'-'.join(['a', 'b', 'c'])
Output
a-b-c
list
Converts a string into a list of its characters.
list(string_name)
Example
string="abc"
list(string)
Output
['a', 'b', 'c']
ljust
Left-justifies a string, padding it with spaces on the right. If the specified width is less than the string length, it returns the original string. The optional second parameter specifies a fill character.
string_name.ljust(width [, fillchar])
Example
name="Andrea Minini"
name.ljust(20, '-')
Output
'Andrea Minini-------'
lower
Converts all characters in the string to lowercase.
string_name.lower()
Example
name="Andrea Minini"
name.lower()
Output
'andrea minini'
lstrip
Removes leading spaces from a string. If a character is specified, it removes that character from the start of the string.
string_name.lstrip(char)
Example
name="Andrea Minini"
name.lstrip('A')
Output
'ndrea Minini'
replace
Replaces a substring with another substring within the string. The optional count parameter specifies the start position for the search.
string_name.replace(old, new[, count])
Example
name="Andrea Minini"
name.replace('Minini', 'Rossi')
Output
'Andrea Rossi'
rfind
Searches for a substring from the right. Returns the position of the first occurrence from the right. Returns -1 if not found. Optional parameters define the start and end positions for the search.
string_name.rfind(sub [, start [, end]])
Example
name="Andrea Minini"
name.rfind('ni')
name.find('ni')
Output
11
9
The rfind method finds the last occurrence, while the find method finds the first.
rindex
Similar to rfind but raises a ValueError if the substring is not found. Optional parameters define the start and end positions for the search.
string_name.rindex(sub [, start [, end]])
Example
name="Andrea Minini"
name.rindex('ni')
name.index('ni')
Output
11
9
rjust
Right-justifies a string, padding it with spaces on the left. If the specified width is less than the string length, it returns the original string. The optional second parameter specifies a fill character.
string_name.rjust(width [, fillchar])
Example
name="Andrea Minini"
name.rjust(20, '-')
Output
'-------Andrea Minini'
rsplit
Splits a string into a list of elements using the specified separator. If no separator is specified, the method defaults to space, splitting the string into words. The optional maxsplit parameter limits the number of elements from the right.
string_name.rsplit([sep [, maxsplit]])
Example
name="Andrea Minini"
name.rsplit("n", 1)
name.split("n", 1)
Output
['Andrea Mini', 'i']
['A', 'drea Minini']
What is the difference between split and rsplit?
If the maxsplit parameter is not specified, split and rsplit give the same result. Otherwise, split breaks the string from the left (e.g., ['A', 'drea Minini']) while rsplit breaks it from the right (e.g., ['Andrea Mini', 'i']).
rstrip
Removes a specified substring or character from the end of the string (right strip). If no character is specified, the method defaults to space.
string_name.rstrip([chars])
Example
name="Andrea Minini"
name.rstrip("ni")
Output
'Andrea M'
split
Splits the string into a list of elements using the specified separator. If no separator is specified, the method defaults to space, splitting the string into words. The optional maxsplit parameter limits the number of elements from the left.
string_name.split([sep [, maxsplit]])
Example
name="Andrea Minini"
name.split("n")
Output
['A', 'drea Mi', 'i', 'i']
splitlines
Splits the string into a list of elements at line breaks. Each list element is a line of text. The line break character \n is not included unless the optional keepends parameter is specified.
string_name.splitlines([keepends])
Example
name="Andrea Minini \n second line"
name.splitlines()
name.splitlines(1)
Output
['Andrea Minini ', ' second line']
['Andrea Minini \n', ' second line']
startswith
Returns true if the string starts with the specified prefix. Optional parameters define the start and end positions for the check.
string_name.startswith(prefix [, start [, end]])
Example
name="Andrea Minini"
name.startswith("And")
name.startswith("And", 4, 8)
Output
true
false
strip
Removes the specified character or substring from the beginning and end of a string. If the character is not specified, the method defaults to removing spaces.
string_name.strip([chars])
Example
name="--Andrea Minini--"
name.strip("-")
Output
Andrea Minini
swapcase
Swaps the case of all characters in the string, converting uppercase to lowercase and vice versa.
string_name.swapcase()
Example
name="Andrea Minini"
name.swapcase()
Output
'aNDREA mININI'
title
Returns the string with each word's first letter capitalized and the remaining letters in lowercase.
string_name.title()
Example
name="andrea minini"
name.title()
Output
'Andrea Minini'
translate
Returns the string with characters mapped through a translation table. The specified characters are removed.
string_name.translate(table[, deletechars])
upper
Converts all characters in the string to uppercase.
string_name.upper()
Example
name="Andrea Minini"
name.upper()
Output
'ANDREA MININI'
zfill
Pads the string on the left with zeros to reach a specified width. If the string is longer than the specified width, it returns the original string.
string_name.zfill(width)
Example
name="Andrea Minini"
name.zfill(20)
Output
'0000000Andrea Minini'