Sometimes, we want to replace multiple substrings of a string with Python
In this article, we’ll look at how to replace multiple substrings of a string with Python.
How to replace multiple substrings of a string with Python?
To replace multiple substrings of a string with Python, we can call replace with each string we want to replace.
For instance, we write
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
to loop through the dic dictionary.
We get the key and value as a tuple with items.
In the loop, we call text.replace with the string i in text that we want to replace with j.
Conclusion
To replace multiple substrings of a string with Python, we can call replace with each string we want to replace.