Categories
Python Answers

How to replace multiple substrings of a string with Python?

Spread the love

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.

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 *