python-regexHow to quote in Python regex?
Python regex can be used to quote strings. To quote a string, use the re.escape()
function. This function takes a string as an argument and returns a string with all non-alphanumeric characters escaped.
For example:
import re
string = "This is a string with special characters!"
escaped_string = re.escape(string)
print(escaped_string)
Output example
This\ is\ a\ string\ with\ special\ characters\!
Code explanation
import re
: imports there
module which contains there.escape()
functionstring = "This is a string with special characters!"
: assigns the string to be quoted to thestring
variableescaped_string = re.escape(string)
: calls there.escape()
function and assigns the returned string to theescaped_string
variableprint(escaped_string)
: prints the escaped string
Helpful links
More of Python Regex
- How to perform a zero length match with Python Regex?
- How to get all matches from a regex in Python?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to validate an IP using Python regex?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
- How to match a URL using Python regex?
See more codes...