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?
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']
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 😐
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?
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']
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 😐