Here is a simple way to replace all instances of characters in a string in Python:
final_string = original_string.replace('original_value', 'new_value')
And if you want to replace n number of instances (where n is the number of instances needed):
final_string = original_string.replace('original_value', 'new_value', n)
Examples of Replacing Instances of Characters in a String in Python
Example 1: Simple replacement of instances in a string
Let’s suppose that you have the following string:
original_string = 'aayyccyyeeyy' print(original_string)
Here is the original string:
aayyccyyeeyy
Now let’s say that you wish to replace all instances of ‘yy‘ with ‘xx‘.
Here is the script that you may use to perform the replacement:
original_string = 'aayyccyyeeyy' final_string = original_string.replace('yy', 'xx') print(final_string)
As you can see, all the instances of ‘yy’ were replaced with ‘xx’ as follows:
aaxxccxxeexx
Example 2: Replacement of n instances
Now let’s replace only the first 2 instances of yy with xx:
original_string = 'aayyccyyeeyy' final_string = original_string.replace('yy', 'xx', 2) print(final_string)
Notice that only the first 2 instances of ‘yy’ (out of 3 instances) were replaced:
aaxxccxxeeyy
Example 3: Replacement of special characters
The same principles covered above can be applied when replacing special characters.
For example, let’s replace all instances of ‘:’ with ‘,’ as follows:
original_string = 'aa:cc:ee' final_string = original_string.replace(':', ',') print(final_string)
The result:
aa,cc,ee
And if you want to replace only the first 2 instances:
original_string = 'aa:cc:ee:dd' final_string = original_string.replace(':', ',', 2) print(final_string)
The result:
aa,cc,ee:dd