1

The fr prefix can combine f and r flag.
But when it comes to the regex's exact match, it seems that it can't format the raw string well:

import re

RE1 = r'123'
RE2 = re.compile(fr'@{3} {RE1}')

Then, the RE2.pattern will become '@3 123',

but what I want is '@{3} 123'.

2
  • What is your intended meaning for @{3}? Is the 3 a placeholder, or is this literal text? Commented Mar 6, 2019 at 3:48
  • @TimBiegeleisen the @{3} means exact match @ 3 times here, 3 is not a placeholder. Commented Mar 6, 2019 at 4:23

2 Answers 2

3

You have to escape the braces surrounding the 3 like this, otherwise they will be interpreted as string interpolation:

import re

RE1 = r'123'
RE2 = re.compile(fr'@{{3}} {RE1}')
print(RE2)

This produces:

@{3} 123

Ref: https://www.python.org/dev/peps/pep-0498/

Note that the correct way to have a literal brace appear in the resulting string value is to double the brace:

>>> f'{{ {4*10} }}'
'{ 40 }'
>>> f'{{{4*10}}}'
'{40}'
Sign up to request clarification or add additional context in comments.

Comments

0

RE2 = re.compile(r'@{3} '+RE1)

Works for me, observe:

RE2.pattern

'@{3} 123'

Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.