Skip to content

Instantly share code, notes, and snippets.

@0xallie
Last active February 14, 2024 01:22
Show Gist options
  • Save 0xallie/07d81cea6d164a2e660bbb43e58e89f9 to your computer and use it in GitHub Desktop.
Save 0xallie/07d81cea6d164a2e660bbb43e58e89f9 to your computer and use it in GitHub Desktop.
import re
def fstring(s):
"""Parse f-string expressions and return the formatted version.
This lets you replace f'...' with fstring('...') and have it work on Python versions older than 3.6.
Note that this is just a fun project rather than a serious one, and may not be perfect, but feel free to use it.
Example:
>>> name = 'John'
>>> fstring('Hello, {name}!')
'Hello, John!
"""
fields = re.findall(r'(?<!\{)\{([^}]+)\}(?!\})', s)
for field in fields:
field = field.split(':')[0]
if field.endswith('='):
s = s.format(**{field: '{0}{1!r}'.format(field, eval(field[:-1]))})
else:
s = s.format(**{field: eval(field)})
s = re.sub(r'\{\{([^}]+)\}\}', r'{\1}', s)
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment