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 chain the string replace method.

For instance, we write:

strs = "abc&def#ghi"
s = strs.replace('&', '\&').replace('#', '\#')
print(s)

We call strs.replace with '&' and '\&' to replace & and '\&'.

And then we call it again to replace '#' with '\#'.

Finally, we assign the returned string to s.

Therefore, s is 'abc\&def\#ghi'.

Conclusion

To replace multiple characters in a string with Python, we can chain the string replace method.

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 *