Qiao
Qiao

Reputation: 17049

Using "r" with variables in re.sub

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.

Upvotes: 5

Views: 20338

Answers (3)

Ωmega
Ωmega

Reputation: 43683

Keep r'...'

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

or go with

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

Upvotes: 2

NPE
NPE

Reputation: 500703

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.

Upvotes: 7

Alexey Feldgendler
Alexey Feldgendler

Reputation: 1810

Short answer: you should keep the r together with the string.

The r prefix is part of the string syntax. With r, Python doesn't interpret backslash sequences such as \n, \t etc inside the quotes. Without r, you'd have to type each backslash twice in order to pass it to re.sub.

r'\]\n'

and

'\\]\\n'

are two ways to write same string.

Upvotes: 6

Related Questions