3

Say you wanted to create a pattern that matches sequences of var consecutive digits. You could do it this way:

p = re.compile(r"\d{"+str(var)+"}")

or this way:

p = re.compile(r"\d{%d}" % var)

But how would you do it using format()?

I tried both:

p = re.compile(r"\d{0}".format(var))

and:

p = re.compile(r"\d{{0}}".format(var))

but none of these worked.

Marco
  • 313
  • 1
  • 2
  • 11
  • I'd just like to add that there's nothing *wrong* per se with using `%`, even though `.format` is generally better. – Dietrich Epp Jan 30 '17 at 17:28

1 Answers1

5

You need to actually have triple { and } - two for the escaped literal braces and one for the placeholder:

In [1]: var = 6

In [2]: r"\d{{{0}}}".format(var)
Out[2]: '\\d{6}'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195