Sometimes, we want to replace multiple substrings of a string in Python.
In this article, we’ll look at how to replace multiple substrings of a string in Python.
How to replace multiple substrings of a string in Python?
To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.
For instance, we write:
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
new_sentence = replace_all(my_sentence, d)
print(new_sentence)
to create the replace_all
function.
We loop through the dic
dictionary’s key-value pairs which are returned by dic.items
.
Then we call text.replace
with i
and j
, which is the original substring and the replacement substring respectively.
And we assign the new returned string to text
.
Finally, we return text
which has all the replacements done.
Next, we call replace_all
with my_sentence
and d
.
And new_sentence
is 'This is my pig and this is my pig.'
.
Conclusion
To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.