Categories
Python Answers

How to input a regex in string.replace with Python?

Spread the love

Sometimes, we want to input a regex in string.replace with Python.

In this article, we’ll look at how to input a regex in string.replace with Python.

How to input a regex in string.replace with Python?

To input a regex in string.replace with Python, we can use the re.sub method.

For instance, we write

import re

line = re.sub(r"</?\[\d+>", "", line)

to call re.sub to replace the characters listed in the regex with empty strings in the line string.

We replace slashes,. questions marks, opening square brackets and digits with empty strings.

Conclusion

To input a regex in string.replace with Python, we can use the re.sub 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 *