Python String Replace

A few years ago, the Google company officially renamed to “Alphabet”. Imagine you’re asked to rename all occurrences of the name “Google” with the occurrences of the name “Alphabet” in internal documents. Would you do it by hand?

Of course, you wouldn’t! Fortunately, Python’s str.replace() method comes to help to replace occurrences of a substring in an original string. This article shows you exactly how to use it.

Basic Usage

>>> "Python Python Python Python".replace("Python", "Finxter", 3)
'Finxter Finxter Finxter Python'

How does the str.replace(old, new) method work in Python?

In its most basic form, it replaces all occurrences of the substring old in the string str with the substring new. For example, the expression "Hi Google".replace("Google", "Alphabet") results in the string "Hi Alphabet". You can also specify a third integer argument to define how often to replace substring old with new in the original string str.

Before we learn about the technical details of the str.replace method, let’s have a look at a few practical examples.

Basic Code Examples

These three examples show the most basic usages of the string replace method in Python:

>>> "Hi Google".replace("Google", "Alphabet")
'Hi Alphabet'
>>> "Hi Google, Google".replace("Google", "Alphabet")
'Hi Alphabet, Alphabet'
>>> "Hi Google, Google".replace("Google", "Alphabet", 1)
'Hi Alphabet, Google'

The first two examples show that the string replace method replaces all occurrences of the first string argument (“Google”) with the second string argument (“Alphabet”) — not only the first occurrence.

The last example shows how you can replace only the first occurrence of the string argument “Google”—by specifying a third argument that indicates the maximum number of replacements.

Next, we’ll learn about the technical details of the string replace method in Python.

Syntax

The str.replace(old, new, count) method searches the string str from left to right and replaces the first count occurrences of the string old with the string new.

Syntax:

str.replace(old, new, count)

Arguments:

  • str — the string to be modified.
  • old — the substring to be searched and replaced.
  • new — the substring that should replace occurrences of old.
  • count (optional) — the number of times we replace strings old with new. If count is not specified, the default value is Infinity: all occurrences are replaced.

Return value:

The str.replace(old, new, count) method returns a new string after count replacements of the old by the new substring were performed.

Related Questions

Let’s explore some related questions you may have regarding the str.replace() method.

Do I Need to Import the String Replace Method in Python?

No, the str.replace() method is a Python built-in method which means that you don’t have to import any library. Just use it out of the box.

Does Python’s String Replace Method Support Regular Expressions (Regex)?

No. This wouldn’t make sense because if you’re fine with the performance penalty of regular expressions, you can directly use the regular expression module re to accomplish the same thing without the string.replace() method.

Replace substring that matches pattern pattern with substring new in the original string str by using the re.sub(pattern, new, str):

import re

s = "Python Python Py"
print(re.sub("(Python|Py)", "Finxter", s))
# Finxter Finxter Finxter

In the code, we replace all matches of the regex (Python|Py) with the replacement string 'Finxter'.

How to Replace a Character in a String at a Certain Index?

To replace the character at position i with string 'x' in string str, simply use the slice notation str[:i] + 'x' + str[i+1:]. Here’s an example where we replace the character at position 3 with string 'i'.

>>> s = 'Finxter Finxter Finxter'
>>> s[:3] + 'i' + s[4:]
'Finiter Finxter Finxter'

If you’re unsure about how slicing works in Python, read the following slicing tutorial on the Finxter blog.

How to Remove the Last Character from a String in Python?

This problem is a special instance of the last problem. You can replace the last character from a string with the following method:

Use slicing s = s[:-1] to create a new string that does not include the last character of the string s. The negative index -1 means that the last position is skipped when slicing string s. Then assign the result to the original string s.

Here’s an example:

>>> s = 'My name is'
>>> s = s[:-1]
>>> print(s)
My name i

The last character from the string s is removed.

How to Remove a Character from a String in Python?

Use the string.replace('c', '') to replace all occurrences of character 'c' in string string. Here’s an example:

>>> 'ccc d ccc d ccc d ccc'.replace('c', '')
' d  d  d '

By replacing all occurrences of character 'c' with the empty string '', we essentially remove them from the original string.

How to Remove Spaces from a String in Python?

Python strings have no remove() method. Instead, you can simply use the string.replace(' ', '') method to replace all spaces with an empty string.

Here’s an example:

>>> 'Solving puzzles with Finxter is fun'.replace(' ', '')
'SolvingpuzzleswithFinxterisfun'

You see, there’s no need for a separate remove method because the replace method does just fine.

How to Replace a Substring in a Python String?

To replace a substring, you use the substring as the first argument of the replace method. Say, you want to replace the substring 'hello' in the original string 'hello world, hello!' with the replacement string 'hi'. Here’s how you’d accomplish that:

>>> 'hello world, hello!'.replace('hello', 'hi')
'hi world, hi!'

The replace method searches for all occurrences of the substring 'hello' and replaces them with the new string 'hi'.

Where to Go From Here?

This question was answered on the Finxter Instagram account. Follow us for continuous improvement in Python!