Replace All Instances of Characters in a String – Python

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:

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

Assume that you have the following string:

original_string = "aayyccyyeeyy"

print(original_string)

Here is the original string:

aayyccyyeeyy

To replace all instances of “yy” with “xx“:

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

Next, 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, replace all instances of “:” with “,” as follows:

original_string = "aa:cc:ee:dd"

final_string = original_string.replace(":", ",")

print(final_string)

The result:

aa,cc,ee,dd

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

Leave a Comment