Python String Methods with Examples

white and black printer paper

Python string is a commonly used type. There are many things you want to do with the strings in your Python projects. This is why Python comes in with useful built-in string methods. To be more specific, there are 47 of them.

These Python string methods can save the day when working with strings.

In this guide, you find a cheat sheet of Python string methods followed by accurate descriptions and examples of each.

A Cheat Sheet of Python String Methods

This table is a cheat sheet of Python string methods.

Below this table you find a more detailed description of each method. In addition, you find an useful example or two on each method.

Method NameMethod Description
capitalizeConverts the first character of a string to upper case
casefoldConverts a string to a lowercase string. Supports more conversions than the lower method. Use when localizing or globalizing strings.
centerReturns a centered string
countReturns how many times a character or substring occurs in a string
encodeReturns an encoded version of a string
endswithChecks if a string ends with the specific character or substring
expandtabsSpecifies a tab size for a string and returns it
findSearches for a specific character or substring. Returns the position of where it was first encountered.
formatThe old-school way to add variables inside of a string. Formats a string by embedding values into it and returning the result
format_mapFormats specific values in a string
indexSearches for a character or substring in a string. Returns the index at which it was first encountered.
isalnumChecks if all the characters of the string are alphanumeric
isalphaChecks if all the characters of the string are found in the alphabetical
isasciiChecks if all the characters of the string are ASCII values
isdecimalChecks if all the characters of the string are decimal numbers
isdigitChecks if all the characters of the string are numeric digits
isidentifierChecks if a string is an identifier
islowerChecks if all characters of a string are lower case
isnumericChecks if all characters of a string are numeric
isprintableChecks if all characters of a string are printable
isspaceChecks if all characters of a string are white spaces
istitleChecks if a string follows title capitalization rules (every word begins with a capital letter)
isupperChecks if all characters of a string are upper case
joinJoins items of an iterable (such as a list) to the end of a string
ljustReturns a left-justified version of a string
lowerConvert a string to lowercase
lstripReturns a left trim version of a string
maketransReturns a translation table of a string for translations
partitionBreaks a string to parts of three. The desired center part is specified as an argument
removeprefixRemoves a prefix from the beginning of a string and returns the string without it.
removesuffixRemoves a suffix from the end of a string and returns the string without it.
replaceReturns a string where a specific character or substring is replaced with something else
rfindSearches a string for a specific character or substring. Returns the last index at which it was found
rindexSearches a string for a specific character or substring. Returns the last index at which it was found.
rjustReturns a right-justified version of a string
rpartitionBreaks a string to parts of three. The desired center part is specified as an argument
rsplitSplits the string at a specific separator, and returns the parts as a list
rstripCreates and returns a right trim version of a string
splitSplits the string at the specified separator, and returns the parts as a list
splitlinesSplits a string at line breaks and returns the lines as a list
startswithChecks if a string starts with the specified character or a substring
stripReturns a trimmed version of a string
swapcaseSwaps cases. All uppercase characters become lowercases and vice versa
titleConverts each word of a string to start with an uppercase letter
translateReturns a translated string
upperConverts a string to upper case
zfillPrefills a string with 0 values

So there you have all the Python string methods. Let’s next take a deeper look at each.

All Python String Methods with Examples

This section shows a more detailed description on each string method there is. In addition, you are going to see some examples of using each.

capitalize

To capitalize the first letter, use the built-in capitalize() method.

"hello, world".capitalize() # Hello, world

This method creates a new string by running through each letter of a string and capitalizing it.

casefold

To convert a Python string to lowercase, use the built-in casefold() method.

For example:

"HELLO, WORLD".casefold() # hello world

This method creates a new string by running through the string and switching each character to lower case.

The difference between casefold() and lower() is that casefold() knows how to convert other language’s special letters. In other words, using casefold() is meaningful when your app needs to support globalization or localization.

For example, a let’s case fold a German sentence to get rid of the big double s (ß) sign. This is not possible using the lower() method:

"Eine Großes bier".lower()    # eine großes bier"
"Eine Großes bier".casefold() # eine grosses bier"

center

Use the center() method to surround a string with characters.

The syntax for using this method is:

string.center(num_characters, separator)

When you call this method, you need to specify the number of total characters, and the character that will surround the string.

For example, let’s add dashes around a word and make it 20 characters long.

txt = "banana"
x = txt.center(20, "-")
print(x)

Output:

-------banana-------

count

The count() method counts how many times a character or a substring occurs in a string.

For example, let’s count the number of letter l’s in a sentence:

"Hello, world".count("l") # Returns 3

Or let’s count how many times the word “Hello” occurs in the sentence:

"Hello, world".count("Hello") # Returns 1

encode

To encode a string, use the built-in encode() method.

The syntax of using this method is:

string.encode(encoding=encoding, errors=errors)

By default, this method encodes the string to UTF-8. If it fails, it throws an error.

For example, let’s convert a string to UTF-8 encoding:

title = 'Hello world'
print(title.encode())

Output:

b'Hello world'

You can call this method with two optional parameters:

  • encoding. This specifies which encoding type is used.
  • errors. This specifies the response when encoding fails.

There are 6 types of errors:

  • strict
  • ignore
  • replace
  • xmlcharrefreplace
  • backslashreplace
  • namereplace

Here are some ASCII encoding examples with different error character types:

txt = "My name is Kimi Räikkönen"

print(txt.encode(encoding="ascii", errors="ignore"))
print(txt.encode(encoding="ascii", errors="replace"))
print(txt.encode(encoding="ascii", errors="xmlcharrefreplace"))
print(txt.encode(encoding="ascii", errors="backslashreplace"))
print(txt.encode(encoding="ascii", errors="namereplace"))

Output:

b'My name is Kimi Rikknen'
b'My name is Kimi R?ikk?nen'
b'My name is Kimi Räikkönen'
b'My name is Kimi R\\xe4ikk\\xf6nen'
b'My name is Kimi R\\N{LATIN SMALL LETTER A WITH DIAERESIS}ikk\\N{LATIN SMALL LETTER O WITH DIAERESIS}nen'

endswith

To check if a string or a proportion of it ends with a character or a substring, use the endswith() method.

For example:

sentence = "Hello, welcome to my world."
print(sentence.endswith("."))

Output:

True

expandtabs

You can specify the tab size with the expandtabs() method. This method is useful if your strings contain tabs.

For example

sentence = "H\te\tl\tl\to"

print(sentence.expandtabs(1))
print(sentence.expandtabs(2))
print(sentence.expandtabs(3))
print(sentence.expandtabs(4))
print(sentence.expandtabs(5))

Output:

H e l l o
H e l l o
H  e  l  l  o
H   e   l   l   o
H    e    l    l    o

find

The find() method finds the index of the first occurrence of a character or substring in a string. If there is no match, it returns -1.

You can also specify a range from where the search is done. The complete syntax for using this method is:

string.find(value, start, end)

For example:

sentence = "Hello world"
x = sentence.find("world")

print(x)

Output:

6

This says that the string "world" can be found at the index of 6 from the sentence.

As another example, let’s search for a substring in a given range:

sentence = "This is a test"
x = sentence.find("is", 3, 8)

print(x)

Output:

5

format

The format() method formats a string by embedding values into it. This is an old-school approach to string formatting in Python.

The format() method is used with the following syntax:

string.format(value1, value2, ... , valuen)

Where the values are variables that are embedded into the string. In addition to this, you need to specify a placeholder for these variables into the string.

Let’s see an example:

name = "John"
age = 21

sentence = "My name is {} and I am {} years old".format(name, age)

print(sentence)

Output:

My name is John and I am 21 years old

format_map

To directly format a dictionary of values into a string, use the format_map() method.

The syntax:

string.format_map(dict)

To make this work, you need to specify placeholders into the string where the values of the dictionary are embedded.

For example:

data = {"name": "John", "age": 21}

sentence = "My name is {name} and I am {age} years old".format_map(data)

print(sentence)

Output:

My name is John and I am 21 years old

index

The index() method finds the index of the first occurrence of a character or substring in a string. It raises an exception if it does not find the value.

You can also specify a range from where the search is done.

The syntax for using this method is:

string.index(value, start, end)

For example:

sentence = "Hello world"
x = sentence.index("world")

print(x)

Output:

6

This says that the string "world" can be found at the index of 6 from the sentence.

As another example, let’s search for a substring in a given range:

sentence = "This is a test"
x = sentence.index("is", 3, 8)

print(x)

Output:

5

The difference between index() and find() methods is that index() raises an error if it does not find a value. The find() method returns -1.

isalnum

To check if all the characters of a string are alphanumeric, use the isalnum() method.

For example:

sentence = "This is 50"
print(sentence.isalnum())

Output:

False

isalpha

To check if all the characters of a string are letters, use the isalpha() method.

For example:

sentence = "Hello"
print(sentence.isalpha())

Output:

True

isascii

To check if all the characters of a string are ASCII characters, use the isascii() method.

For example:

sentence = "Hello"
print(sentence.isalpha())

Output:

True

isdecimal

To check if all the characters of a string are decimal characters, use the isdecimal() method.

For example:

sentence = "\u0034"
print(sentence.isdecimal())

Output:

True

isdigit

To check if all the characters of a string are numbers, use the isdigit() method.

For example:

sentence = "34"
print(sentence.isdigit())

Output:

True

isidentifier

To check if all the characters of a string are identifiers, use the isidentifier() method.

  • A string is considered an identifier if it contains alphanumeric letters (a-z, 0-9) or underscores.
  • An identifier cannot start with a number.

For example:

sentence = "Hello"
print(sentence.isidentifier())

Output:

True

islower

To test if a string is in lowercase, use the built-in islower() method:

For example:

"Hello, world".islower() # False

This method checks if all the characters of a string are in lowercase. If they are, it returns True. Otherwise, False.

isnumeric

To check if all the characters of a string are numeric, use the isnumeric() method.

For example:

sentence = "5000"
print(sentence.isnumeric())

Output:

True

isprintable

To check if all the characters of a string are printable, use the isprintable() method.

For example:

sentence = "This a is test"
print(sentence.isprintable())

Output:

True

isspace

To check if all the characters of a string are white spaces, use the isspace() method.

For example:

sentence = "             "
print(sentence.isspace())

Output:

True

istitle

To check if all the first characters of each word in a string start with capital letter, use the istitle() method.

For example:

sentence = "Hello There This Is A Test"
print(sentence.istitle())

Output:

True

isupper

To test if a string is in uppercase, use the built-in isupper() method:

For example:

"HELLO, WORLD".isupper() # True

This method checks if all the characters of a string are in uppercase. If they are, it returns True. Otherwise, False.

join

To join a group of items to one string, use the join() method.

For example:

words = ["This", "is", "a", "test"]
sentence = " ".join(words)

print(sentence)

Output:

This is a test

ljust

Add specific characters, such as empty spaces, to the right of a string with the ljust() method.

The syntax:

string.ljust(num_characters, separator)
  • num_characters is the total length of the strings plus the added characters
  • separator is the character that is added n times to the string.

For example, let’s add dashes to the right of a string:

print("Hello".ljust(20, "-"))

Output:

Hello---------------

lower

To convert a Python string to lowercase, use the built-in lower() method.

For example:

"HELLO, WORLD".lower() # hello world

This method creates a new string by running through the string and switching each character to lower case.

lstrip

To remove leading characters from a string, use lstrip() method.

By default, this method removes all the white spaces from the beginning of a string.

For example:

print("    test".lstrip())

Output:

test

As another example, let’s remove all the dashes from the beginning of this string:

print("---test---".lstrip("-"))

Output:

test---

maketrans

To create a string mapping table, use the maketrans() method. This mapping table is used with the translate() method.

The syntax:

string.maketrans(a, b, c)

Where:

  • The first parameter a is required. If only this parameter is specified, it has to be a dictionary that specifies how strings are replaced. Otherwise a needs to be a string that specifies which characters to replace.
  • The second parameter b is optional. It must be the same length with a. Each character in a will be replaced by a corresponding character in b
  • The third parameter c is also optional. It describes which characters to remove from the original string.

For instance, let’s replace “o” characters with “x” in a sentence:

sentence = "Hello World"
trans_table = sentence.maketrans("o", "x")

print(sentence.translate(trans_table))

Output:

Hellx Wxrld

partition

To split a string to three parts, use the partition() method. It works by splitting a string around a specific character or substring.

For example, you can partition a sentence around a given word:

sentence = "This is a test"
parts = sentence.partition("a")

print(parts)

Output:

('This is', 'a', 'test')

removeprefix

To remove a string from the beginning, use the removeprefix() method. Notice this is quite a new method and only works for Python 3.9+.

For example, let’s remove word “This” from a sentence:

sentence = "This is a test"

print(sentence.removeprefix("This"))

Output:

is a test

removesuffix

To remove a string from the the end, use the removesuffix() method. Notice this is quite a new method and only works for Python 3.9+.

For example, let’s remove word “test” from the end of a sentence:

sentence = "This is a test"

print(sentence.removesuffix("test"))

Output:

This is a

replace

To replace a string with another inside a string, use the replace() method.

The syntax:

string.replace(old, new, count)

Where:

  • old is the string you want to replace.
  • new is the new string you want to replace occurences of old.
  • count is an optional parameter. It specifies how many occurences you want to replace.

For example:

sentence = "This is a test"
updated_sentence = sentence.replace("This", "It")

print(updated_sentence)

Output:

It is a test

rfind

Find the last occurrence of a substring or character inside a string using the rfind() method. If no occurrences are found, this method returns -1.

The syntax:

string.rfind(val, start, end)

Where:

  • val is the string you are looking for
  • start is an optional parameter. It defines the start index for a search
  • end is also an optional parameter. It defines the end index for the search.

For example:

sentence = "This car is my car"
last_index = sentence.rfind("car")

print(last_index)

Output:

15

rindex

Find the last occurrence of a substring or character inside a string using the rindex() method. If no occurrences are found, this method returns raises an exception.

The syntax:

string.rindex(val, start, end)

Where:

  • val is the string you are looking for
  • start is an optional parameter. It defines the start index for a search
  • end is also an optional parameter. It defines the end index for the search.

For example:

sentence = "This car is my car"
last_index = sentence.rindex("car")

print(last_index)

Output:

15

rjust

Add specific characters, such as empty spaces, to the left of a string with the rjust() method.

The syntax:

string.rjust(num_characters, separator)
  • num_characters is the total length of the strings plus the added characters
  • separator is the character that is added n times to the string.

For example, let’s add dashes to the beginning of a string:

print("Hello".rjust(20, "-"))

Output:

---------------Hello

rpartition

Split a string into three parts based on the last occurrence of a specific string. These parts are returned as a tuple.

For example:

sentence = "This car is my car, you cannot drive it"

parts = sentence.rpartition("car")
print(parts)

Output:

('This car is my ', 'car', ', you cannot drive it')

rsplit

To split a string into a list from the right, use rsplit() method.

The syntax:

string.rsplit(separator, max)

Where:

  • separator is the separator based on which the string is split
  • max is the maximum number of times the split is done. It is an optional parameter. If you don’t specify max, this method works like split().

For example, let’s split a comma-separated string from the right. But let’s only split at the first comma it encounters:

items = "apple, banana, cherry"
split_items = items.rsplit(",", 1)

print(split_items)

Output:

['apple, banana', ' cherry']

Notice how there are only two strings in this array.

rstrip

Remove trailing characters at the end of a string using the rstrip() method.

If no argument is specified, this method tries to remove empty strings at the end of a string.

For example, let’s remove dashes from a string:

print("Hello-----".rstrip("-"))

Output:

Hello

split

Split a string into a list using the split() method. This is one of the most commonly used Python string methods.

By default this method splits the string based on empty spaces.

The syntax:

string.split(separator, max)

Where:

  • separator is an optional parameter. It is the character or substring based on which the string is split into parts.
  • max is also an optional parameter. It defines how many splits the method is going to do.

For example:

sentence = "This is a test"

# split by white spaces 
parts = sentence.split()

print(parts)

Output:

['This', 'is', 'a', 'test']

As another example, let’s split a comma-separated list two times for the first two commas encountered:

sentence = "Apple, Banana, Orange, Mango, Pineapple"

parts = sentence.split(",", 2)

print(parts)

Output:

['Apple', ' Banana', ' Orange, Mango, Pineapple']

Notice how there are only 3 elements in the split list.

splitlines

To split a string at line breaks, use the splitlines() method.

sentence = "Apple\nBanana\nOrange\nMango\nPineapple"

parts = sentence.splitlines()

print(parts)

Output:

['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']

You can also keep the line breaks at the end of each string. To do this, pass True into the call:

sentence = "Apple\nBanana\nOrange\nMango\nPineapple"

parts = sentence.splitlines(True)

print(parts)

Output:

['Apple\n', 'Banana\n', 'Orange\n', 'Mango\n', 'Pineapple']

startswith

To check if a string starts with a specific value, use the startswith() method.

The syntax:

string.startswith(val, start, end)

Where:

  • val is the value you want to check if the string starts with
  • start is an optional parameter. It is an integer that specifies from where to start the check in the string
  • end is also an optional parameter. It is an integer that specifies where to end the search.

For instance:

sentence = "Hello world"

print(sentence.startswith("Hello"))

Output:

True

Let’s take a look at another example. This time let’s see if the 5th character starts with “wor”:

sentence = "Hello world"

print(sentence.startswith("wor", 6))

Output:

True

strip

To remove specific characters or substrings from a string, use the strip() method. By default this method removes blank spaces. You can also specify it an argument that specifies what to remove.

For instance, let’s remove all the dashes from a string:

word = "--------test---"

stripped_word = word.strip("-")

print(stripped_word)

Output:

test

swapcase

To make lowercase letters to upper and uppercase letters to lower, use the swapcase() method.

For example:

"HELLO, world".swapcase() # hello, WORLD

This method creates a string by looping through the string and swapping all uppercase letters to lowercase and vice versa.

title

To capitalize the first letter of each word in a string, use the title case converter by calling title() method.

For example:

"hello, world".title() # Hello, World

This method creates a new string by looping through a string and capitalizing each words’ first letter.

translate

To replace specific characters of a string with another, use the translate() method.

Before you do that, create a mapping table with the maketrans() method.

For example, let’s replace “o” letters with “x”:

sentence = "Hello World"
trans_table = sentence.maketrans("o", "x")

print(sentence.translate(trans_table))

upper

To convert a Python string to uppercase, use the built-in upper() method.

For example:

"Hello, world".upper() # HELLO WORLD

This method creates a new string by looping through a string and changing each character to upper case.

zfill

Add leading zeros to a string with zfill() method.

Give this method the desired length of the string. It fills the string with zeros until the desired length is achieved.

For example:

word = "Test"

filled_word = word.zfill(10)

print(filled_word)

Output:

000000Test

Notice how the total length of this string is now 10.

Conclusion

That’s a heck a lot of Python string methods. Do not even try to remember each of them. Instead, feel free to bookmark this article to refer back to it later.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *