find character n times in string, without hard coding n

Question:

I am trying to find a character that repeats n times in a string. However, because the n is set a constant rather than a specific number, it does not work.

eg:

re.findall("A{2}", "TAA")

outputs: ["AA"]

but

n=2
re.findall("A{n}", "TAA")

outputs: []

How do I make the second example work, without hard coding n?

Asked By: t197453

||

Answers:

Try using an f-string.

a=re.findall(f"A{n}", "TAA")


As pointed out in the comments – f-string formatting doesn’t work due to overloading of curly brackets.

I tried using .replace with some success, but it’s not as tidy as @jasonharper’s suggestion in the comments – not least for having to convert the int n into a string:

n=2
a=re.findall("A{n}".replace("n",str(n)), "TAA")
>> ['AA']
Answered By: Thomas Kimber

Try this.

import re
n = 2
a = re.findall('A{{{}}}'.format(n), "TAA")
print(a)

reference

Answered By: ConstantinHong

Try using a raw f string:

import re
n = 2
a = re.findall(fr'A{{{n}}}', "TAA")
print(a)
>>> ['AA']

In an f string, raw curly braces need to be doubled, so in this case, we need triples: the f string replaces the {n} with a 2, and replaces the doubled {{ with a single. Raw f strings are weird 😐

Answered By: Danielle M.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.