As you already know, the string is one of the most important data types in Python. To make working with strings easier, Python has many special built-in string methods. We are about to learn some of them.
An important thing to remember, however, is that the string is an immutable data type! This means that you cannot just change the string in-place, so most string methods return a copy of the string (with several exceptions). To save the changes made to the string for later use, you need to create a new variable for the copy that you made or assign the same name to the copy. So, what to do with the output of the methods depends on whether you are going to use the original string or its copy later.
"Changing" a string
The first group of string methods consists of those that "modify" the string in a specific way. These methods return a new copy of the string with the specified changes, while leaving the original string unchanged.
The syntax for calling a method is as follows:
string.method_name(arguments)
or
variable_name.method_name(arguments)
Where string is the actual string, variable_name is a variable holding a string, method_name is the name of the method being called, and arguments are any additional parameters the method may require.
Here's a list of common string methods in this category:
str.replace(old, new, count)replaces all occurrences of theoldstring with thenewone. Thecountparameter is optional, and if specified, only the firstcountoccurrences are replaced in the given string.str.upper()converts all characters of the string to upper case.str.lower()converts all characters of the string to lower case.str.title()converts the first character of each string to upper case.str.swapcase()converts upper case to lower case and vice versa.str.capitalize()changes the first character of the string to upper case and the rest to lower case.
And here's an example of how these methods are used (note that we don't save the result of every method):
message = "bonjour and welcome to Paris!"
print(message.upper()) # BONJOUR AND WELCOME TO PARIS!
# `message` is not changed
print(message) # bonjour and welcome to Paris!
title_message = message.title()
# `title_message` contains a new string
# with the first character of each word capitalized
print(title_message) # Bonjour And Welcome To Paris!
print(message.replace("Paris", "Lyon")) # bonjour and welcome to Lyon!
replaced_message = message.replace("o", "!", 2)
print(replaced_message) # b!nj!ur and welcome to Paris!
# again, the source string is unchanged, only its copy is modified
print(message) # bonjour and welcome to Paris!Removing characters from a string
When reading a string from a source (such as a file or user input), you often need to edit it to retain only the necessary information. For example, the input string may contain excessive whitespace or unwanted characters at the beginning or end. Three useful "editing" methods to help clean up such strings are:
str.lstrip([chars])removes the leading characters (i.e. characters from the left side). If the argumentcharsisn’t specified, leading whitespaces are removed.str.rstrip([chars])removes the trailing characters (i.e. characters from the right side). The default for the argumentcharsis also whitespace.str.strip([chars])removes both the leading and the trailing characters. The default is whitespace.
The chars argument, when specified, is a string containing characters that should be removed from either the beginning or end of the string (depending on the method you're using). Here's how it works:
whitespace_string = " hey "
normal_string = "incomprehensibilities"
# delete spaces from the left side
whitespace_string.lstrip() # "hey "
# delete all "i" and "s" from the left side
normal_string.lstrip("is") # "ncomprehensibilities"
# delete spaces from the right side
whitespace_string.rstrip() # " hey"
# delete all "i" and "s" from the right side
normal_string.rstrip("is") # "incomprehensibilitie"
# no spaces from both sides
whitespace_string.strip() # "hey"
# delete all trailing "i" and "s" from both sides
normal_string.strip("is") # "ncomprehensibilitie"
Keep in mind that the methods strip(), lstrip(), and rstrip() get rid of all possible combinations of specified characters:
word = "Mississippi"
# starting from the right side, all "i", "p", and "s" are removed:
print(word.rstrip("ips")) # "M"
# the word starts with "M" rather than "i", "p", or "s", so no chars are removed from the left side:
print(word.lstrip("ips")) # "Mississippi"
# "M", "i", "p", and "s" are removed from both sides, so nothing is left:
print(word.strip("Mips")) # ""
Use them carefully, or you may end up with an empty string.
Summary
To sum up, we have considered the main methods for strings. Here is a brief recap:
While working with strings, you have to remember that strings are immutable, thus all the methods that "change" them only return the copy of a string with necessary changes.
If you want to save the result of a method call for later use, you need to assign this result to a variable (either the same or the one with a different name).
If you want to use this result only once, for example, in comparisons or just to print the formatted string, you are free to use the result on the spot, as we did within
print().
Read more on this topic in Working with Python Strings on Hyperskill Blog.