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.