23 Python String Methods Every Developer Should Know
Discover the 23 most-used string methods in Python. Level up your skills now and become a better developer!
• 13 min
Introduction
Before diving into Python’s string functions, it’s essential to be well familiar with the exact definition of what a string is.
In simple terms, a string is a data type used to describe textual content rather than numbers across different programming languages. It’s mainly made up of a pre-defined collection of characters, including whitespace and numeric digits, and is usually delimited by single or double quotes to set it apart during a program’s execution.
String literals in Python have no maximum length limit and depend only on your computer’s memory resources.
In Python, indices can be used to access individual characters in a string. Users are also allowed to access characters in a string using both positive and negative address references, which is a unique feature. Positive indices grant access to characters from the start of the string, while negative indices allow access to characters from the end.
Python’s string data type comes with a large set of pre-defined methods. These functions let you modify and work with string literals in Python easily.
For example, if you want to convert every character of your string to lowercase, there’s a better way to do it than iterating through every character of the string.
This can easily be achieved in a single line using Python’s lower() method, which does exactly that. That’s how these methods prove useful in real life.
This article will focus on the main built-in string methods in Python, with surprisingly useful applications for manipulating strings in data structures and algorithms.
1. len
Used to count the total number of characters in a string.
Syntax:
len(<string>)Example:
text = "How many characters are here?"
print(len(text))
# 302. capitalize
The capitalize() method returns a new, modified string, converting the first character of the original string to uppercase and the rest to lowercase.
Syntax:
<string>.capitalize()Example:
text = "tExt tO bE cHangeD"
print(text.capitalize())
# Text to be changed3. upper
Returns a new string with all characters in uppercase.
Syntax:
<string>.upper()Example:
text = "text to make uppercase"
print(text.upper())
# TEXT TO MAKE UPPERCASE4. lower
Returns a new string with all characters in lowercase.
Syntax:
<string>.lower()Example:
text = "TEXT TO MAKE lowercase"
print(text.lower())
# text to make lowercase5. count
The count() method is used to count how many times a given string appears in a piece of text.
Syntax:
string.count(search_text)
string.count(search_text, start)
string.count(search_text, start, end)This method has three arguments. The first is required, and the other two are optional. The first argument holds the value to search for in the text. The second argument holds the search’s start position, and the third argument holds the search’s end position.
Example:
The following script shows the three different uses of the count() method. The first call will search for the word ‘is’ in the strVal variable. The second call searches for the same word starting from position 20. The third call searches for the same word within the range from position 50 to 100.
strVal = 'Python is a powerful programming language. It is very simple to use. It is an excellent language for beginners to learn programming.'
print("The word 'is' appeared %d times" %(strVal.count("is")))
# The word 'is' appeared 3 times
print("The word 'is' appeared %d times after position 20" %(strVal.count("is", 20)))
# The word 'is' appeared 2 times after position 20
print("The word 'is' appeared %d times within the range 50 to 100" %(strVal.count("is", 50, 100)))
# The word 'is' appeared 1 times within the range 50 to 1006. find
Returns the position/index of the first occurrence of a substring in a given string. Otherwise, it returns -1.
Syntax:
find(search_text)
find(search_text, start_position)
find(search_text, start_position, end_position)This method can take three arguments, where the first is required and the other two are optional. The first argument holds the string value to search for, the second defines the search’s start position, and the third defines the search’s end position. It returns the position of search_text if it exists in the main string; otherwise, it returns -1.
Example:
The uses of the find() method with one, two, and three arguments are shown in the following script. The first output will be -1 because the search text is ‘python’ and the str variable holds the string ‘Python’. The second output will return a valid position because the word ‘program’ exists after position 10. The third output will return -1 because the word ‘Python’ doesn’t exist within the string’s range of 0 to 5.
str = 'Learn programming in Python'
print(str.find('python'))
# -1
print(str.find('Python'))
# 22
print(str.find('program', 8))
# 8
print(str.find('Python', 0, 5))
# -1
7. rfind
In Python, the rfind() method is used to find the last occurrence of a substring. It works similarly to the find() method, but starts searching from the end of the string toward the beginning. If the substring is found, the method returns the position of the last occurrence. Otherwise, it returns -1.
Syntax:
string.rfind(substring)
string.rfind(substring, start)
string.rfind(substring, start, end)
Example:
text = "Python is a programming language, Python is great."
# Find the last occurrence of "Python"
position = text.rfind("Python")
print("Position of the last occurrence of 'Python':", position)
# Position of the last occurrence of 'Python': 36
# Start searching from position 20
position = text.rfind("Python", 20)
print("Position of the last occurrence of 'Python' from position 20:", position)
# Position of the last occurrence of 'Python' from position 20: 36
# Limit the search up to position 25
position = text.rfind("Python", 0, 25)
print("Position of the last occurrence of 'Python' up to position 25:", position)
# Position of the last occurrence of 'Python' up to position 25: 0
8. startswith
Checks whether a given string starts with a specific prefix or not, and returns true or false.
Syntax:
<string>.startswith(substring)Example:
text = "Dessert"
text.startswith("Des")
# True
text.startswith("des")
# False9. endswith
Checks whether a given string ends with a specific suffix or not, and returns true or false.
Syntax:
<string>.endswith(substring)Example:
text = "constitutionally"
text.endswith("Ally")
# False
text.endswith("ally")
# True10. index
The index() method works like the find() method, but there’s one key difference between them. Both methods return the position of the search text if the string exists within the main string. If the search text doesn’t exist in the main string, the find() method returns -1, but the index() method raises a ValueError.
Syntax:
<string>.index(search_text [, start [, end]])This method has three arguments. The first is required and holds the search text. The other two are optional and hold the search’s start and end positions.
Example:
The index() method is used four times in the following script. A try-except block is used here to handle the ValueError. The index() method is used with one argument in the first output, searching for the word ‘powerful’ in the strVal variable. Next, the index() method searches for the word ‘programming’ starting from position 10, which exists in strVal. Then, the method searches for the word ‘is’ between positions 5 and 15. The last index() call searches for the word ‘his’ at 025, which doesn’t exist in strVal.
strVal = 'Python is a powerful programming language.'
try:
print(strVal.index('powerful'))
# 12
print(strVal.index('programming', 10))
# 21
print(strVal.index('is', 5, 15))
# 7
print(strVal.index('his', 0, 25))
# The search string was not found
except ValueError:
print("The search string was not found")
11. split
This method is used to split any string data based on a specific separator or delimiter. It can take two arguments, both optional.
Syntax:
<string>.split()
<string>.split(separator)
<string>.split(separator, maxsplit=maxsplit)If this method is used without any arguments, a space is used as the separator by default. Any character or a list of characters can be used as a separator. The second, optional argument is used to set the limit on how many times the string will be split. It returns a list of strings.
Example:
s1 = 'string methods in python programming language'.split()
# ['string', 'methods', 'in', 'python']
s2 = 'string methods in python programming language'.split(' ', maxsplit=1)
# ['string', 'methods in python']12. rsplit
Just like the split method, rsplit is used to split any string data based on a specific separator or delimiter. It can also take two arguments, both optional.
Syntax:
<string>.rsplit()
<string>.rsplit(separator)
<string>.rsplit(separator, maxsplit=maxsplit)Example:
s = 'string methods in python'.rsplit()
# ['string', 'methods', 'in', 'python']
s = 'string methods in python'.rsplit(' ', maxsplit=1)
# ['string methods in', 'python']
13. join
The join() method is used to create a new string by combining other strings with a string, list of strings, or tuple of strings.
Syntax:
separator.join(iterable)It only takes one argument, which can be a string, a list, or a tuple, and the separator holds the string value used for the concatenation.
Example:
The strip() method is used to remove whitespace from both sides of a string.
names = ["Alice", "Bob", "Charlie", "David"]
formatted_names = ", ".join(names)
print("Formatted list of names:", formatted_names)
# Formatted list of names: Alice, Bob, Charlie, David13. strip
The strip() method is used to remove whitespace from both sides of a string. This method takes no arguments.
Syntax:
<string>.strip()
<string>.rStrip()Example:
text = " Text with whitespace at the start and end. "
text.strip()
# "Text with whitespace at the start and end."14. lstrip
The lstrip() method removes whitespace from the left side.
Syntax:
<string>.lstrip()Example:
text = " Text with whitespace at the start and end. "
text.lstrip()
# "Text with whitespace at the start and end. "15. rstrip
The rstrip() method removes whitespace from the right side of the string.
Syntax:
<string>.rstrip()Example:
text = " Text with whitespace at the start and end. "
text.rstrip()
# " Text with whitespace at the start and end."16. removeprefix
Python’s removeprefix method is used to remove a specified prefix from a string. If the string starts with the prefix, the prefix is removed; otherwise, the original string is kept unchanged.
Syntax:
<string>.removeprefix(substring)Example:
text = "Python is great"
result = text.removeprefix("Python is ")
print(result)
# "great"17. removesuffix
Python’s removesuffix method is used to remove a specific suffix from a string. If the string ends with the suffix, that suffix is removed; otherwise, the original string remains unchanged.
Syntax:
<string>.removesufix(substring)Example:
text = "Winter is coming."
result = text.removesuffix(" is coming.")
print(result)
# "Winter"18. replace
The replace() method is used to replace a specific part of a string with another string, if a match is found. It can take three arguments, two required and one optional.
Syntax:
<string>.replace(search_string, replacement_string [, limit])The first argument is the search string you want to replace, and the second argument is the replacement string. The third, optional argument sets the limit for how many occurrences get replaced.
Example:
In the following script, the first replace is used to replace the word ‘PHP’ with the word ‘Java’ in the content of the str variable. Since the search word exists in the str variable, the word ‘PHP’ will be replaced with the word ‘Java’. The third argument of the replace method is used in the next replace, and it will replace only the first match of the search word.
text = "I like PHP, but I like Python more"
replaced = text.replace("PHP", "Java")
print("Original string:", text)
# Original string: I like PHP, but I like Python more
print("Replaced string:", replaced)
# Replaced string: I like Java, but I like Python more
replaced_2 = text.replace("like", "dislike", 1)
print("\nOriginal string:", text)
# Original string: I like PHP, but I like Python more
print("Replaced string:", replaced_2)
# Replaced string: I dislike PHP, but I like Python more19. format
The format() method is an essential method in Python for producing formatted output. It has many uses and can be applied to both string and numeric data to produce formatted output. How this method can be used for index-based formatting of string data is shown in the following example.
Syntax:
{}.format(value)The string and placeholder position are defined within curly braces ({}). It returns the formatted string based on the string and the values passed in the placeholder position.
Example:
The four types of formatting are shown in the following script. In the first result, the index value {0} is used. No position is assigned in the second result. Two sequential positions are assigned in the third result. Three unordered positions are set in the fourth result.
# Example 1: Direct substitution with index
print("Learn to program in {0}.".format("Python"))
# Learn to program in Python.
# Example 2: Substitution without specifying indices
print("\nBoth {} and {} are scripting languages".format("Bash", "Python"))
# Both Bash and Python are scripting languages
# Example 3: Substitution with indices
print("\nStudent ID: {0}\nStudent name: {1}\n".format("00001", "John Doe"))
# Student ID: 00001
# Student name: John Doe20. center
Returns a string centered within a specified length. Padding is done using the specified character (the default is a space).
Syntax:
<string>.center(width [, char])Example:
s = 'Python is amazing!'
s = s.center(30, '-')
# ------Python is amazing!------21. ljust
Returns the string left-justified within a string of specified length. Padding is done using the specified character (the default is a space).
Syntax:
<string>.ljust(width [, char])Example:
s = 'Python is amazing!'
s = s.ljust(30, '-')
# Python is amazing!------------22. rjust
Returns the string right-justified within a string of specified length. Padding is done using the specified character (the default is a space).
Syntax:
<string>.rjust(width [, char])Example:
s = 'Python is amazing!'
s = s.rjust(30, '-')
# ------------Python is amazing!23. partition
In Python, the partition() string method looks for a specific substring within a string and splits the original string into a tuple containing three elements.
- The first element holds the part of the string before the specified substring.
- The second element holds the specified substring.
- The third element holds the remaining part after the substring.
Syntax:
<string>.partition(substring)Example:
sentence = "The cat chases the mouse in the garden."
substring = "mouse"
result = sentence.partition(substring)
print(result)
# ["The cat chases the ", "mouse", " in the garden."]Conclusion
In summary, mastering Python’s string methods is an essential skill for any programmer, as it enables effective text manipulation, playing a critical role in areas ranging from text analysis to web development. Knowing these tools not only improves your code’s efficiency and readability but also opens the door to creativity, making it possible to build innovative solutions and solve complex challenges. Investing time in learning and refining these methods, then, is key to becoming a more competent and versatile programmer.
Summary
| Method | Use |
|---|---|
| len | Counts the total number of characters in a string. |
| capitalize | Converts the first character to uppercase and the rest to lowercase. |
| upper | Returns a new string with all characters in uppercase. |
| lower | Returns a new string with all characters in lowercase. |
| count | Counts how many times a specific string appears in the string. |
| find | Returns the position of the first occurrence of a substring. |
| rfind | Returns the position of the last occurrence of a substring. |
| startswith | Checks whether the string starts with a specific prefix. |
| endswith | Checks whether the string ends with a specific suffix. |
| index | Works like the find() method, but raises a ValueError if not found. |
| split | Splits the string based on a specific separator or delimiter. |
| rsplit | Splits the string based on a specific separator or delimiter, starting from the end. |
| join | Creates a new string by combining other strings with a separator. |
| strip | Removes whitespace from both sides of the string. |
| lstrip | Removes whitespace from the left side of the string. |
| rstrip | Removes whitespace from the right side of the string. |
| removeprefix | Removes a specific prefix from a string. |
| removesuffix | Removes a specific suffix from a string. |
| replace | Replaces a specific part of a string with another, if a match is found. |
| format | Produces formatted output based on index for string data. |
| center | Returns a string centered within a specified length. |
| ljust | Returns the string left-justified within a specified length. |
| rjust | Returns the string right-justified within a specified length. |
| partition | Splits the string into a tuple containing three elements based on a specific substring. |
Citations
- 15 insanely useful string methods in Python.Sandipan Das
- 31 essential String methods in Python you should know.Patrick Loeber