- Python String replace() Method
- Syntax
- Parameters
- Return Value
- Example
- Example
- Example
- Python String replace() Method
- Syntax
- Parameter Values
- More Examples
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Python String.Replace() – Function in Python for Substring Substitution
- What does the .replace() Python method do?
- How does the .replace() Python method work? A Syntax Breakdown
- Python .replace() Method Code Examples
- How to Replace All Instances of a Single Character
- How to Replace Only a Certain Number of Instances of a Single Character
- How to Replace All Instances of a String
- How to Replace Only a Certain Number of Instances of a String
- How to Perform Case-Insensitive Substring Substitution in Python
- Wrapping up
Python String replace() Method
The Python String replace() method replaces all occurrences of one substring in a string with another substring. This method is used to create another string by replacing some parts of the original string, whose gist might remain unmodified.
For example, in real-time applications, this method can be used to replace multiple same spelling mistakes in a document at a time.
This replace() method can also replace selected number of occurrences of substrings in a string instead of replacing them all.
Syntax
Following is the syntax for Python String replace() method −
Parameters
- old − This is old substring to be replaced.
- new − This is new substring, which would replace old substring.
- count − If this optional argument count is given, only the first count occurrences are replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Example
The following example shows the usage of Python String replace() method.
str = "Welcome to Tutorialspoint" str_replace = str.replace("o", "0") print("String after replacing: " + str_replace)
When we run above program, it produces following result −
String after replacing: Welc0me t0 Tut0rialsp0int
Example
When we pass the substring parameters along with the optional count parameter, the method only replaces the first count occurrences in the string.
In this example below, the input string is created and the method takes three arguments: two substrings and one count value. The return value will be the string obtained after replacing the first count number of occurrences.
str = "Fred fed Ted bread and Ted fed Fred bread." strreplace = str.replace("Ted", "xx", 1) print("String after replacing: " + strreplace)
When we run above program, it produces following result −
String after replacing: Fred fed xx bread and Ted fed Fred bread.
Example
When we pass two substrings and count = 0 as parameters to the method, the original string is returned as the result.
In the following example, we created a string «Learn Python from Tutorialspoint» and tried to replace the word «Python» with «Java» using the replace() method. But, since we have passed the count as 0, this method does not modify the current string, instead of that, it returns the original value («Learn Python from Tutorialspoint»).
str = "Learn Python from Tutorialspoint" strreplace = str.replace("Python", "Java", 0) print("String after replacing: " + strreplace)
If you execute the program above, the outpit is displayed as −
String after replacing: Learn Python from Tutorialspoint
Python String replace() Method
The replace() method replaces a specified phrase with another specified phrase.
Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Syntax
Parameter Values
Parameter | Description |
---|---|
oldvalue | Required. The string to search for |
newvalue | Required. The string to replace the old value with |
count | Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences |
More Examples
Example
Replace all occurrence of the word «one»:
txt = «one one was a race horse, two two was one too.»
Example
Replace the two first occurrence of the word «one»:
txt = «one one was a race horse, two two was one too.»
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Python String.Replace() – Function in Python for Substring Substitution
Dionysia Lemonaki
In this article you’ll see how to use Python’s .replace() method to perform substring substiution.
You’ll also see how to perform case-insensitive substring substitution.
What does the .replace() Python method do?
When using the .replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify.
The .replace() method returns a copy of a string. This means that the old substring remains the same, but a new copy gets created – with all of the old text having been replaced by the new text.
How does the .replace() Python method work? A Syntax Breakdown
The syntax for the .replace() method looks like this:
string.replace(old_text, new_text, count)
- old_text is the first required parameter that .replace() accepts. It’s the old character or text that you want to replace. Enclose this in quotation marks.
- new_text is the second required parameter that .replace() accepts. It’s the new character or text which you want to replace the old character/text with. This parameter also needs to be enclosed in quotation marks.
- count is the optional third parameter that .replace() accepts. By default, .replace() will replace all instances of the substring. However, you can use count to specify the number of occurrences you want to be replaced.
Python .replace() Method Code Examples
How to Replace All Instances of a Single Character
To change all instances of a single character, you would do the following:
phrase = "I like to learn coding on the go" # replace all instances of 'o' with 'a' substituted_phrase = phrase.replace("o", "a" ) print(phrase) print(substituted_phrase) #output #I like to learn coding on the go #I like ta learn cading an the ga
In the example above, each word that contained the character o is replaced with the character a .
In that example there were four instances of the character o . Specifically, it was found in the words to , coding , on , and go .
What if you only wanted to change two words, like to and coding , to contain a instead of o ?
How to Replace Only a Certain Number of Instances of a Single Character
To change only two instances of a single character, you would use the count parameter and set it to two:
phrase = "I like to learn coding on the go" # replace only the first two instances of 'o' with 'a' substituted_phrase = phrase.replace("o", "a", 2 ) print(phrase) print(substituted_phrase) #output #I like to learn coding on the go #I like ta learn cading on the go
If you only wanted to change the first instance of a single character, you would set the count parameter to one:
phrase = "I like to learn coding on the go" # replace only the first instance of 'o' with 'a' substituted_phrase = phrase.replace("o", "a", 1 ) print(phrase) print(substituted_phrase) #output #I like to learn coding on the go #I like ta learn coding on the go
How to Replace All Instances of a String
To change more than one character, the process looks similar.
phrase = "The sun is strong today. I don't really like sun." #replace all instances of the word 'sun' with 'wind' substituted_phrase = phrase.replace("sun", "wind") print(phrase) print(substituted_phrase) #output #The sun is strong today. I don't really like sun. #The wind is strong today. I don't really like wind.
In the example above, the word sun was replaced with the word wind .
How to Replace Only a Certain Number of Instances of a String
If you wanted to change only the first instance of sun to wind , you would use the count parameter and set it to one.
phrase = "The sun is strong today. I don't really like sun." #replace only the first instance of the word 'sun' with 'wind' substituted_phrase = phrase.replace("sun", "wind", 1) print(phrase) print(substituted_phrase) #output #The sun is strong today. I don't really like sun. #The wind is strong today. I don't really like sun.
How to Perform Case-Insensitive Substring Substitution in Python
Let’s take a look at another example.
phrase = "I am learning Ruby. I really enjoy the ruby programming language!" #replace the text "Ruby" with "Python" substituted_text = phrase.replace("Ruby", "Python") print(substituted_text) #output #I am learning Python. I really enjoy the ruby programming language!
In this case, what I really wanted to do was to replace all instances of the word Ruby with Python .
However, there was the word ruby with a lowercase r , which I would also like to change.
Because the first letter was in lowercase, and not uppercase as I specified with Ruby , it remained the same and didn’t change to Python .
The .replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution.
In order to perform a case-insensitive substring substitution you would have to do something different.
You would need to use the re.sub() function and use the re.IGNORECASE flag.
- Use the re module, via import re .
- Speficy a regular expression pattern .
- Mention with what you want to replace the pattern.
- Mention the string you want to perform this operation on.
- Optionally, specify the count parameter to make the replacement more precise and specify the maximum number of replacements you want to take place.
- The re.IGNORECASE flag tells the regular expression to perform a case-insensitive match.
So, all together the syntax looks like this:
import re re.sub(pattern, replace, string, count, flags)
Taking the example from earlier:
phrase = "I am learning Ruby. I really enjoy the ruby programming language!"
This is how I would replace both Ruby and ruby with Python :
import re phrase = "I am learning Ruby. I really enjoy the ruby programming language!" phrase = re.sub("Ruby","Python", phrase, flags=re.IGNORECASE) print(phrase) #output #I am learning Python. I really enjoy the Python programming language!
Wrapping up
And there you have it — you now know the basics of substring substitution. Hopefully you found this guide helpful.
To learn more about Python, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you learned.
Thanks for reading and happy coding!