Skip to content

Python string replace function | Examples code

  • by

With the 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.

Syntax

A simple syntax of “replace” function.

string.replace(oldvalue, newvalue, count)

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 

txt = "EyeHunts Android tutorial"

newTxt = txt.replace("Android", "Python")

print(newTxt)

Output: EyeHunts Python tutorial

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

txt = "Easy EyeHunts Easy Python Easy tutorial"

newTxt = txt.replace("Easy", "Best", 2)

print(newTxt)

Output: Best EyeHunts Best Python Easy tutorial

Python replace integer (Number) Example 

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

txt = "EyeHunts Python 2 tutorial"

newTxt = txt.replace("2", "3")

print(newTxt)

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 “”).

txt = "Replace Python xyz tutorial"

newTxt = txt.replace("xyz ", "")

print(newTxt)

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading