Categories
Python Answers

How to replace multiple characters in a string with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *