Using {} regex within re.sub when using f-string

Hi, I run into an issue when I was trying to use regex with f-string in re.sub

Please see the below code exhibits. When I analyzed more I assumed that when I am using f-string the interpreter tries to resolve {128} as a variable. But I want it to be seen as a regex [0-9,a-f]{128}
How could we achieve that without changing the pattern.
As we can see the same pattern works fine if we remove the f-string and use only regex


str = “”“This is normal string of abcd.yaml
This is second line 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"”"
l = “is”
str = re.sub(r’(This is normal string of abcd.yaml\nThis is second line )[0-9,a-f]{128}',“xyz”,str)
print (str)

xyz

str = “”“This is normal string of abcd.yaml
This is second line 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"”"
l = “is”
str = re.sub(rf’(This {l} normal string of abcd.yaml\nThis is second line )[0-9,a-f]{128}',“xyz”,str)
print (str)

This is normal string of abcd.yaml
This is second line 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678

--------------- This is not the case if the regex pattern is [\w]+ where it works perfectly well --------

str = “”“This is normal string of abcd.yaml
This is second line test”“”
l = “is”
str = re.sub(r’(This is normal string of abcd.yaml\nThis is second line )[\w]+',“xyz”,str)
print (str)

xyz

str = “”“This is normal string of abcd.yaml
This is second line test”“”
l = “is”
str = re.sub(rf’(This {l} normal string of abcd.yaml\nThis is second line )[\w]+',“xyz”,str)
print (str)

xyz

You can quote the {128} as {{128}}

>>> f'Hello {123}'
'Hello 123'
>>> f'Hello {{123}}'
'Hello {123}'
:>>>

Many Thanks Barry, that helps a lot… :slight_smile: