Python String Functions

The built-in library provides various Python string functions and methods that allow us to perform required operations on string data. In this section, we explain a list of string Functions and their functionality.

You can use the Hyperlinks to find detailed information about each one of the Python String methods, along with practical examples.

Introduction to Python String Functions

A Python string is a sequence of Unicode characters enclosed in single or double quotes. It can be a group of letters, multiple words separated by a white space, or a combination of letters and numbers, and so on.

Unlike List, the string is immutable. Therefore, we cannot perform addition or removal operations on the existing one. However, one can perform a slice or concatenate using built-in Python string methods or functions. It always returns a new string, instead of updating the existing one.

Apart from this, it has its own methods for converting a string to uppercase, lowercase, splitting, formatting, joining, and many more. The following sections provide a list of built-in Python String functions or methods with a simple example.

NOTE: For more information on strings, please refer to the Python String article in the Python tutorial.

Python string methods to deal with case

The following string methods help you convert the lowercase letters to uppercase and vice versa. Apart from that, these help check whether the given string is lower or upper.

FunctionsDescription
capitalize()It converts the first character to capitalization and the following characters to Lowercase.
casefold()It returns the given sentence in Lowercase.
islower()TRUE if it has at least one letter, and all the characters are in lowercase.
lower()It converts the given string into Lowercase characters and returns a new one.
isupper()TRUE if the sentence has at least one letter, and all the characters are in Uppercase.
upper()It converts into Uppercase letters and returns a new one.
swapcase()It converts lowercase letters into Uppercase and the uppercase letters into lowercase.
title()It converts the first character in each word to Uppercase and the following characters to Lowercase
istitle()It searches for a specified word and replaces it with a new value.

lower()

The lower() is one of the built-in string functions in Python that returns a copy of a string by converting all characters to lowercase.

s = 'HELLO'
print(s.upper())
hello

islower()

The islower() function checks whether all string characters are lowercase and returns True. Otherwise, it returns False.

s = 'hi'
print(s.islower())
True

upper()

The upper() function converts all characters in a string to uppercase and returns a new string.

s = 'Hello'
print(s.upper())
HELLO

isupper()

The isupper() function checks whether all string characters are uppercase and returns True. Otherwise, it returns False.

s = 'HELLO'
print(s.isupper())
True

Python string methods – capitalize()

The capitalize() function capitalizes (uppercase) the first (leftmost) character and changes the remaining letters to lowercase.

s = 'hello world'
print(s.capitalize())
Hello world

title()

The title() function converts the first character in each word to uppercase and changes the remaining letters to lowercase.

s = 'tutorial gateway'
print(s.title())
Tutorial Gateway

TIP: capitalize() converts only the first character. On the other hand, the title() function converts the first character in each word.

istitle()

The istitle() function returns TRUE if a given string is a title case. It means the first letter in each word should be a capital letter, and the remaining letters are in lowercase.

a = "The United States"
print(a.istitle())
True

swapcase()

The swapcase() function converts lowercase characters to uppercase and vice versa.

s = 'TuTorIaL gAtEwAY'
print(s.swapcase())
tUtORiAl GaTeWay

casefold()

 The casefold() function is similar to the lower() function that converts a given string to lowercase characters. We can use casefold() to perform case-insensitive operations and handle more Unicode letters.

s = 'TuTORiaL GatEWaY'
print(s.casefold())
tutorial gateway

Python String methods to validate Characters

The following string functions do not accept any argument values and perform validation. They return True if all characters are of the given type.

FunctionsDescription
isalnum()This Python string function or method returns TRUE if it contains letters and numbers
isalpha()TRUE if it has at least one letter, and all the characters are Alphabetic
isdecimal()TRUE if it has at least one letter, and all the characters are Decimal.
isdigit()It displays TRUE if the string has at least one letter, and all the letters are Digits.
isidentifier()TRUE if it is a valid identifier. Otherwise, it returns false.
isnumeric()It displays TRUE if it has at least one letter, and all the letters are numeric.
isprintable()This string function or method returns TRUE if all the letters are printable.
isspace()It prints TRUE if the sentence contains only white spaces

Python string functions – isalnum()

The isalnum() function returns TRUE if all characters in a string are alphanumeric, such as a-z, A-Z, or 0-9.

a = 'cat123'
print(a.isalnum())
True

isalpha()

The isalpha() function returns TRUE if all characters in a string are alphabet characters, such as a-z and A-Z.

a = 'dog'
print(a.isalpha())
True

isspace()

The isspace() function returns TRUE if characters in a string are only white spaces.

a = " "
print(a.isspace())
True

isdigit()

The isdigit() function returns TRUE if all characters are digits from 0 to 9. It accepts only digits and some superscripts.

a = '12345'
print(a.isdigit())
True

Python string methods – isnumeric()

The isnumeric() function returns TRUE if all characters are numerical values, and more. It accepts digits, fractions, superscripts, roman numerical, and Unicode numbers (for example, Chinese).

a = "½"
print(a.isnumeric())
True

isdecimal()

The isdecimal() function returns TRUE if all characters are strictly decimal values from 0 to 9.

a = '123'
print(a.isdecimal())
True

isprintable()

The isprintable() function returns True if all characters in a string are printable. Otherwise, it returns False. If it is plain text, it can print. However, if there are any escape characters, it returns False.

a = "I see a cat and a cat can see me."
print(a.isprintable())
True

Isidentifier()

The isprintable() function returns True if a string is a valid identifier. Otherwise, it returns False. A valid identifier means a string starts with letters or underscores, and not with digits.

print("hi".isidentifier())
print("9hi".isidentifier())
True

False

Python String methods to remove unwanted characters

The following string methods help remove unwanted characters from the leading, trailing, and both start and end.

FunctionsDescription
lstrip()It removes the unwanted characters from the Left-hand side.
rstrip()It removes the unwanted characters from the right-hand side.
strip()It removes the trailing and leading unwanted characters from both ends. Performs both lstrip() and rstrip() functions.
removeprefix()It removes a prefix from a given string.
removesuffix()It removes the suffix from a given string.

Python string functions – lstrip()

The lstrip() function removes the leading unwanted characters from a string. By default, it removes white spaces from the left side.

s = '!!!Hello'
print(s.lstrip('!'))
Hello

removeprefix()

The removeprefix() function removes the leading characters in exact order from a string. By default, it removes white spaces from the left side.

a = "abcapple"
print(a.removeprefix("abc"))
apple

rstrip()

The lstrip() function removes the trailing unwanted characters from a string. By default, it removes the right-side white spaces.

s = 'Hello###'
print(s.rstrip('#'))
Hello

Python string methods – removesuffix()

The removesuffix() function removes the trailing characters from a string in the exact order mentioned in an argument.

a = "Hi How are you"
print(a.removesuffix("you"))
Hi How are

strip()

The strip() function performs lstrip() and rstrip() to remove the leading and trailing unwanted characters from a string. By default, it removes white spaces from both the left and right sides.

s = '####Hello#######'
print(s.strip('#'))
Hello

Python string functions – rstrip() vs removesuffix()

The rstrip does not follow the order to remove leading characters. However, the removesuffix() function follows a strict order. If the substring does not match, the removesuffix() returns the whole string.

If we take the example below, the rstrip() function checks for a, b, and c in any order. So, it removes the ending letters, c, c, a, a, b, and c.

a = "applebccaabc"
print(a.rstrip("abc"))
apple

On the other hand, the removesuffix() looks for “abc”. If it finds the “abc” substring in the same order, remove it from the end.

print(a.removesuffix("abc"))
applebcca

Python string functions – lstrip() vs removeprefix()

The lstrip does not follow order when removing leading characters. However, the removeprefix() function follows a strict order. If the substring does not exactly match, it returns the whole string.

If we take the above example, it checks for a, b, and c in any order. So, it removes the starting letters, a, b, c, and a.

a = "abcapple"
print(a.lstrip("abc"))
pple

On the other hand, the removeprefix() function exactly looks for the “abc” substring and removes it from the starting position.

a = "abcapple"
print(a.removeprefix("abc"))
apple

Python String methods to find a substring

The following function performs a string search to locate the substring and returns the index position.

FunctionsDescription
count()It counts how many times the substring occurs.
find()The index position of the first occurrence. Otherwise, it displays -1 if the specified one is not found
index()It returns the index of the first occurrence of a substring.
startswith()TRUE if the sentence starts with the specified substring
endswith()This string function or method displays TRUE if the string ends with the specified substring
rfind()It displays the index position of the Last occurrence (the highest index). It returns -1 if the specified one is not found
rindex()It returns the index position of the Last occurrence. It raises a ValueError if the specified Python text is not found

Python string functions – count()

The count() function returns the total number of times the substring has repeated in a string.

a = 'trip to tutorial gateway'
print(a.count('t'))
5

find()

The find() function returns the index position of the first occurrence of a given substring. It returns -1 if it does not.

s = 'hi hello how are you'
print(s.find('e'))
4

rfind()

The rfind() function returns the last occurrence index position of a given substring. It returns -1 if it does not.

s = 'hi hello how are you'
print(s.rfind('e'))
15

Python string methods – index()

The index() function searches for the first occurrence of a given substring in a string. Next, it returns the index position of the substring starting position. It raises ValueError if it does not find a substring.

a = 'i see a cat and a cat can see me'
print(a.index('cat'))
8

rindex()

The rindex() function returns the last occurrence index position of a given substring starting point in a string. It raises a ValueError if it does not find.

a = 'i see a cat and a cat can see me'
print(a.rindex('cat'))
18

startswith()

The startswith() function checks whether a given string starts with a character or a substring mentioned in the argument. If it starts with ‘H’, returns True. Otherwise, it returns False.

s = 'Hello World'
print(s.startswith('H'))
True

endswith()

The endswith() function checks string ends with a character or a substring. If it ends with ‘World’, returns True. Otherwise, it returns False.

s = 'Hello World'
print(s.endswith('World'))
True

Python String methods for text alignment

The following functions perform string alignment by adjusting the given text.

FunctionsDescription
center()It returns the index position of the first occurrence of a specified substring. It raises a ValueError if the specified one is not found.
ljust()Justify to the Left-hand side and fill the remaining width with default white spaces.
rjust()This string function or method justifies to the Right-hand side and fills the remaining width with default white spaces.
expandtabs()It returns a copy of the given one, where all the tab characters are replaced with one or more spaces.
zfill()This string function prints a copy filled with ASCII ‘0’ digits on the left-hand side of the sentence to make a length to the specified width.

Python string functions – center()

The center() function aligns a given string to the center position and fills the empty gap with white spaces. Here, we have specified a second argument, so the empty spaces will fill with # symbols.

a = 'Info'
b = a.center(11, '#')
print(b)
####Info###

ljust()

The ljust() function aligns a string to the left side and fills the empty gap with the specified character.

a = ‘Info’
print(a.ljust(10, ‘#’))

Info######

rjust()

The rjust() function aligns a string to the right side and fills the gap with the specified character.

a = 'Info'
print(a.rjust(8, '$'))
$$$$Info

Python string methods – zfill()

The zfill() function aligns a string to the right side and pads ‘0’ on the left side to satisfy the length.

a = '123'
print(a.zfill(7))
0000123

expandtabs()

The expandtabs() function replaces the ‘\t’ with whitespaces. By default, it places 8 white spaces. Use an argument to assign one’s own spacing structure.

s = 'hi\thello\thow are you'
print(s.expandtabs())
hi      hello   how are you

Python String methods to perform split and join

FunctionsDescription
rsplit()Split into a list of sentences based on the specified delimiter. It happens from right to left.
split()This string function or method is very useful to Split into a list of substrings based on the specified delimiter
splitlines()It prints a list of lines by breaking the given one at line boundaries.
join()Join (Concatenate) a list of substrings
partition()It partitions the given one at the first occurrence of the specified separator and returns a tuple with three arguments.
rpartition()It partitions the given sentence using the specified separator and returns a tuple with three arguments.

Python string functions – join()

The join() function combines or joins the elements from an iterable, like a list, and creates a string.

a = ['apple', 'kiwi', 'orange']
b = ' '.join(a)
print(b)
apple kiwi orange

split()

The split() function splits a given string into a list of items and returns a list as an output. By default, it uses whitespaces to split. However, you can specify the characters.

s = 'hi hello how are you'
print(s.split())
['hi', 'hello', 'how', 'are', 'you']

rsplit()

The rsplit() function performs splitting from the right side of a string into a list of items. Use the second argument to specify the total number of splits you want from the right side.

It created three list items. From the right side, it splits the string twice based on whitespace. Next, it keeps the remaining string as one list item.

s = 'hi hello how are you'
print(s.rsplit(' ', 2))
['hi hello how', 'are', 'you']

splitlines()

The splitlines() function splits the string at line breaks and returns a list of elements.

s = 'hi\nhello\nhow are you'
print(s.splitlines())
['hi', 'hello', 'how are you']

partition()

The partition() function accepts an argument (separator) and splits the string into three parts. IT returns a tuple containing values before the separator, the separator itself, and the value after the separator.

s = 'apple-kiwi-orange'
print(s.partition('-'))
('apple', '-', 'kiwi-orange')

rpartition()

The rpartition() function is equivalent to the partition() function. However, it performs the partition from the right side.

s = 'apple-kiwi-orange'
print(s.rpartition('-'))
('apple-kiwi', '-', 'orange')

Python string methods to perform replace and format

FunctionsDescription
encode()Prints the encoded version of a string object
format()Useful for formatting strings.
format_map()It uses a dictionary to format the string.
replace()It replaces a substring inside a given string.

encode()

The encode() function converts a given string into bytes. Here, we used the Unicode string “café”.

text = "café"

print(text.encode("utf-8"))
b'caf\xc3\xa9'

format()

The format() function replaces empty flower brackets in a string with the argument values. Hear the first argument replaces the first placeholder and the second replaces the second flower brackets.

a = "The student scored {} out of {}."
print(a.format(580, 600))
The student scored 580 out of 600.

Python string methods – format_map()

The format_map() function takes the dictionary and replaces the key placeholders ({}) with the corresponding values.

data = {
    "name": "Tracy",
    "age": 25
}

text = "Hi, This is {name} and I am {age} years old."
print(text.format_map(data))
Hi, this is Tracy and I am 25 years old.

replace()

The replace() function searches for a given character or substring and replaces it with the second argument value.

s = 'tutorial gateway'
print(s.replace('t', 'M'))
MuMorial gaMeway

Python string functions for transactions

FunctionsDescription
maketrans()It returns the transaction table. We can further use this transaction in the translate() method.
translate()Prints a Copy of the given one, in which each character is mapped with the transaction table.

maketrans()

The maketrans() function creates a mapping table with the two arguments. The ASCII Unicode value of each character in the first argument maps to the second argument value. For example, 97: 49 means a -> 1.

t = str.maketrans("abcd", "1234")
print(t)
{97: 49, 98: 50, 99: 51, 100: 52}

transaction()

It utilizes the transaction table and replaces the existing text with the transaction table values. Here, abcd in the “s” variable is replaced by 1234.

t = str.maketrans("abcd", "1234")
s = "abcdefg"
print(s.translate(t))
1234efg

Common Python string functions

The following are the list of common functions that can be used on strings, tuples, sets, lists, and dictionaries.

FunctionsDescription
len()It returns the string length (including spaces).
min()It returns the minimum character (alphabet) using the ASCII value.
max()It returns the maximum character (alphabet) using the ASCII value.
sorted()It sorts based on the ASCII value and returns a list of individual characters.

Python string functions – len()

The len() function returns the total number of characters (including spaces) in a string.

s = 'Tutorial Gateway'
print(len(s))
16

max()

The max() function uses the ASCII value to find the maximum character in a string. Here, the ASCII value of lowercase y is the largest.

s = 'Gateway'
print(max(s))
y

min()

The min() function uses the ASCII value to identify the minimum character in a string. Here, the ASCII value of uppercase G is the smallest (less than ‘a’).

s = 'Gateway'
print(min(s))
G

sorted()

The sorted() function sorts the given string based on the ASCII value and returns a list of individual characters.
s = 'Gateway'
print(sorted(s))
['G', 'a', 'a', 'e', 't', 'w', 'y']

Real-time Use cases of Python string methods

The following list of examples is basic to familiarize oneself with the working functionality of each function. These are simple examples, yet they are powerful enough to start programming. However, to master yourself on string functions, you must use the hyperlinks to see the powerful practical examples.

How to normalize the User Input

When performing form validation, there are situations where we have to normalize user inputs. In such a case, we can use strip() to remove unwanted leading and trailing empty spaces. Next, use lower() to convert a string to lowercase.

name = '  tutorial      '
norm = name.strip().lower()
print(norm)
tutorial

Python string functions to Extract Domain Name from Email

We can use the split() function to split the email based on the @ symbol and slice the right side part.

email = "[email protected]"
domain = email.split("@")[1].lower()
print(domain)
tutorialgateway.org

TIP: WE can also use partition or rpartition to avoid error when there is no @ symbol.

domain2 = email.partition("@")[2].lower()
print(domain)

Python string functions to Count Words

The strip() function removes extra white spaces. Next, the split() converts the string to a list of items based on white spaces. The len() function counts the total number of list items.

s = '   hi hello how are you   '
words = s.strip().split()
print(words)
print(len(words))
['hi', 'hello', 'how', 'are', 'you']
5

Convert a multi-line string to a single line

As we all know, the splitlines() function splits the string by “\n” and returns a list of items. Next, the join() function accepts those list items convert it to a string.

text = "Hi\nHello\nHow\nAre\nYou"
l = text.splitlines()
print(l)

s = " ".join(l)
print(s)
['Hi', 'Hello', 'How', 'Are', 'You']
Hi Hello How Are You

Python string functions to remove a File Extension

A file consists of a “.” followed by PDF, txt, and CSV extensions. Use the rsplit() function to split the string by “.” and set maximum splits to 1. Use the slicing technique to get the first portion.

filename = "Student_Marks.csv"
name = filename.rsplit(".", 1)[0]
print(name)
Student_Mark

Extract the File Extension

Here, we used the rpartition() function to perform right partition based on “.”. As it returns 3 items, we use [2] to get the last item.

filename = "Student_Marks.csv"
name = filename.rpartition(".")[2]
print(name)
csv

Python string functions to remove https and www from URLS

We can use the removeprefix() function to remove the https://www. from incoming URLS.

domain = "https://www.tutorialgateway.org"
new = domain.removeprefix("https://www.")
print(new)
tutorialgateway.org