37

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!

Peter Varo
  • 11,726
  • 7
  • 55
  • 77

2 Answers2

69

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
orthocresol
  • 657
  • 8
  • 9
Daniel Malachov
  • 1,604
  • 1
  • 10
  • 13
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.

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 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}'```). – Rusca8 Mar 15 '20 at 12:35
  • @Rusca8 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='!')`) – ash17 May 03 '23 at 19:57