Python string replace function | Examples

With Python string replace function, you can replace a particular word or substring(phrase) with another one in a sentence (content). It returns the string where all occurrences of a word or substring are replaced with another word or substring.

Python string replace function | Examples method

This tutorial, you will learn about Python string replace function and it’s examples.


A simple syntax of “replace” function.

Parameter Values

  • old – Substring you want to replace (Required)
  • new – Substring which would replace with the old substring (Required)
  • count – How many times you want to replace, an integer value (optional)

Python string replace function Example 

Output: EyeHunts Python tutorial

Another example – Replaces the first 2 occurrences of the word “Easy” with “Best”.

Output: Best EyeHunts Best Python Easy tutorial

Python replace integer (Number) Example 

The replacing number in python is the same as the string example.

Output: EyeHunts Python 3 tutorial

Remove string using replace() Method

It’s a very easy just add string which you want to remove and for new value not pass anything (blank string “”).

Output: Replace Python tutorial

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of Python string replace are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.