Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "r" with variables in re.sub

Tags:

python

regex

I need to do this:

text = re.sub(r'\]\n', r']', text)

But with find and replace as variables:

find = '\]\n'
replace = ']'
text = re.sub(find, replace, text)

Where should I put r (raw)? It is not a string.

like image 504
Qiao Avatar asked Dec 15 '22 17:12

Qiao


1 Answers

The r'' is part of the string literal syntax:

find = r'\]\n'
replace = r']'
text = re.sub(find, replace, text)

The syntax is in no way specific to the re module. However, specifying regular expressions is one of the main use cases for raw strings.

like image 172
NPE Avatar answered Jan 06 '23 12:01

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!