Python String Replace

5/5 - (6 votes)

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? As a coder, you would automate it! 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.

In its most basic form, the str.replace(old, new) method creates a new string replacing 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". A third integer argument defines how often to replace substring old with new in the original string str.

Python String Replace | A Helpful Guide

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.


str.replace(old, new, count)


  • 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.


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

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

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.

You can try it yourself in our interactive Python shell:

Exercise: Run the code. What’s the output? Change the code to replace only the first three occurrences of the word 'Google'!

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

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'.

Related article: Python Regex Superpower – The Ultimate Guide

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(' ', '')

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'.

Instagram Story of String Replace

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

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!