How to format raw string with different expressions inside?
Asked Answered
J

2

39

Let's say, we want to catch something with regex, using rawstring to define the pattern, which pattern has repeating elements, and variables inside. And we also want to use the format() string formatting form. How to do this?

import re
text = '"""!some text'
re.findall(r'"{3}{symbol}some\stext'.format(symbol='!'), text)

But this line leads us to an IndexError:

# IndexError: tuple index out of range

So, my question is: how to format a raw string if it has formatting curly-braces expression, and repeating curly-braces expression inside?

Thanks in advance!

Josiejosler answered 25/5, 2013 at 22:47 Comment(0)
D
28

Escape the curly brackets with curly brackets

>>> import re
>>> text = '"""!some text'
>>> re.findall(r'"{{3}}{symbol}some\stext'.format(symbol='!'), text)
['"""!some text']

However it is better to just use % formatting in this situation.

Dalesman answered 25/5, 2013 at 22:51 Comment(2)
Just for the sake of completion... if you happened to need a string that has a variable within curly brackets, then you need triple of those. Yes it feels stupid, but I've just needed that for a PyLaTeX project (doc.append(r'\command{{{variable}}}') appends '\command{value}').Naamana
@Naamana this also stands for cases when the number of repetitions refers to some external variable (given rep_num = 3 then r'"{{{rep_num}}}{symbol}some\stext'.format(symbol='!'))Consolatory
S
77

Use f-strings (introduced in Python 3.6):

a = 15
print(fr'Escape is here:\n but still {a}')

# => Escape is here:\n but still 15
Sharp answered 10/10, 2019 at 10:45 Comment(0)
D
28

Escape the curly brackets with curly brackets

>>> import re
>>> text = '"""!some text'
>>> re.findall(r'"{{3}}{symbol}some\stext'.format(symbol='!'), text)
['"""!some text']

However it is better to just use % formatting in this situation.

Dalesman answered 25/5, 2013 at 22:51 Comment(2)
Just for the sake of completion... if you happened to need a string that has a variable within curly brackets, then you need triple of those. Yes it feels stupid, but I've just needed that for a PyLaTeX project (doc.append(r'\command{{{variable}}}') appends '\command{value}').Naamana
@Naamana this also stands for cases when the number of repetitions refers to some external variable (given rep_num = 3 then r'"{{{rep_num}}}{symbol}some\stext'.format(symbol='!'))Consolatory

© 2022 - 2024 — McMap. All rights reserved.