Menu Close

How to replace multiple characters in a string with Python?

Sometimes, we want to replace multiple characters in a string with Python.

In this article, we’ll look at how to replace multiple characters in a string with Python.

How to replace multiple characters in a string with Python?

To replace multiple characters in a string with Python, we can use the string translate and str.maketrans methods.

For instance, we write

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

to call str.maketrans with a dict that has the keys of the substrings to look for.

And we replace them with the strings in the values,

Then we call s.translate with the object returned by maketrans to do the replacement of the values and return a new string with the replacement done.

Conclusion

To replace multiple characters in a string with Python, we can use the string translate and str.maketrans methods.

Posted in Python, Python Answers