Python String Replace

Posted 

3 min read

In this article, we will talk about how to replace a substring inside a string in Python, using the replace() method.

.replace() Method

In Python, strings are represented as immutable str objects. The str class comes with many methods that allow you to manipulate strings.

The .replace() method takes the following syntax:

str.replace(old, new[, maxreplace])
  • str - The string you are working with.
  • old – The substring you want to replace.
  • new – The substring that replaces the old substring.
  • maxreplace – Optional argument. The number of matches of the old substring you want to replace. The matches are counted from the beginning of the string.

The method returns a copy of the string srt with some or all matches of substring old replaced by new. If maxreplace is not given, all occurrences are be replaced.

In the example below we’re replacing the substring far in string s with miles:

s = 'A long time ago in a galaxy far, far away.'s.replace('far', 'miles')

The result is a new string:

'A long time ago in a galaxy miles, miles away.'
String literals are usually enclosed by single quotes, although double quotes can be used too.

When the optional maxreplace argument is given, it will limit the number of replaced matches. In the following example we’re replacing only the first occurrence:

s = 'My ally is the Force, and a powerful ally it is.'s.replace('ally', 'friend', 1)

The result string will look like this:

'My friend is the Force, and a powerful ally it is.'

To delete a substring, use an empty string '' as a replacement. For example to remove space from the following string you would use:

s = 'That’s no moon. It’s a space station.'s.replace('space ', '')

The new string will look like the following:

`That’s no moon. It’s a station.'

Replace Substring in List of Strings

To replace a substring in a list of strings, use the list comprehension construct as show below:

s.replace('old', 'new') for s in list

Let’s take a look at the following example:

names = ['Anna Grace', 'Betty Grace', 'Emma Grace']new_names = [s.replace('Grace', 'Lee') for s in names]print(new_names)

The code above creates a copy of the list with all occurrences of substring Grace replaced by Lee:

['Anna Lee', 'Betty Lee', 'Emma Lee']

Conclusion

Replacing a substring in a string is one of the most basic operations when writing code in Python. After reading this tutorial, you should have a good understanding of how to use the replace() method.

If you have any questions or feedback, feel free to leave a comment.