Skip to content

Instantly share code, notes, and snippets.

@DarkMatterMatt
Last active June 23, 2018 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarkMatterMatt/58188943cecb550e7b9bbe0fe082665c to your computer and use it in GitHub Desktop.
Save DarkMatterMatt/58188943cecb550e7b9bbe0fe082665c to your computer and use it in GitHub Desktop.
Converts all Python 3.6 fstrings f"insert {var:.2f} here" to Python 3.5 compatible string.format "insert {:.2f} here".format(var)
##############################################################################
## 3.6_fstring-3.5_strformat.py ##
## Matt Moran (2018) ##
##############################################################################
## Usage: python 3.6_fstring-3.5_strformat.py file_to_process.py
##
## Converts all 3.6 fstrings f"insert {var:.2f} here" to 3.5 compatible
## "insert {:.2f} here".format(var)
##
## Works with:
## single and triple quoted strings f"""{var}"""
## format specifiers f'{var:.2f}'
##
## DOES NOT WORK WITH:
## literal braces f"{{this is a string}}"
## strings that open and close multiple times f"{x}" "continues" "here"
##
#!/usr/bin/env python3
import re
import sys
# get filename passed from command line
filename = sys.argv[1]
# strings that open with ' and " triple quoted strings
fstring_patterns = [r'f"(.*)?"', r"f'(.*)?'", "f'''(.*)?'''", 'f"""(.*)?"""']
brace_pattern = re.compile(r'{([^:{]+)(:[^}]+)?}')
# open and read input file
with open(filename, "r") as f:
fread = f.read();
# loop through each fstring regex pattern
for fstring_pattern in fstring_patterns:
# loop through the file finding matches
for pattern_match in re.finditer(fstring_pattern, fread):
string = pattern_match.group(0)[1:] # cut starting f off the string
variables = []
# get all the brace expressions in each match
for n in brace_pattern.finditer(string):
# extract format specifier
format = n.group(2) if n.group(2) else ""
# remove group 1, the name of the variable
string = string.replace(n.group(0), "{" + format + "}")
# save the variable to a list to pass to format
variables.append(n.group(1))
# make the string, with the .format bit
string += ".format(" + ", ".join(variables) + ")"
# replace the old fstring with the new string.format
fread = fread.replace(pattern_match.group(0), string)
# write the output
filename = filename.rsplit(".", 1)
with open(filename[0] + "_out." + filename[1], "w") as f:
f.write(fread)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment