How to replace characters in a string in Python
📋 Table Of Content
In this article, we will see how to replace a character in a string in python with some examples.
In python, to find and replace a single character or a word in python, we can use the
The replace method takes in two parameters:
- The word you want to replace.
- The word you want to replace with.
string.replace(oldchr, newchr, count)
oldchr = the character/word we want to find in the string.
newchr = the character/word to replace the oldchr with.
count = how many times we want to replace a word/character from a string.
Replace a character in a String
Here, is an example to replace a single character in a string using the
replace() method in python.
str = "Hello this is a message for everyone" # replace the word everyone print(str.replace("everyone", "you")) # original string print(str)
Here, we have used
replace() method to replace the word "everyone" with the word "you". This method does not change the original string, it creates a new string with the new changes.
The output will be like this:
Hello this is a message for you Hello this is a message for everyone
Note: Python string are immutable which means we cannot alter the content of the string once assigned.
We can also control the number of times we want a word or a character to change in a string using the
replace() method along with the count option.
Let's see an example to understand it better.
str = "one cake, two cake, three cake" # replace the word cake print(str.replace("cake", "ball", 2))
The output is
one ball, two ball, three cake
Here, by setting the count to
2, we have told the method to change the word "cake" to "ball" only
two times in the string.
Next, if we want to change every occurrence of the word "cake" to a "ball", then we can just leave the
count option blank.
countoption in the method is not specified, then the method replaces every occurrence of the word in the string.
str = "one cake, two cake, three cake" # replace the word cake print(str.replace("cake", "ball"))
The output is:
one ball, two ball, three ball
- Check for prime number using for and while loop in Python
- Merge two dictionaries together using python (3 ways)
- Merge multiple JSON objects into one single object in Python
- Python - Check if list is empty or not
- Python - Insert an element at specific index in a list