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.
This tutorial, you will learn about Python string replace function and it’s examples.
A simple syntax of “replace” function.
string.replace(oldvalue, newvalue, count)
- 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)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Examples of Python string replace are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.