Skip to content

Instantly share code, notes, and snippets.

@maedoc
Created August 20, 2017 19:54
Show Gist options
  • Save maedoc/3ec2d287b5d7cf8b07939a09b2183b37 to your computer and use it in GitHub Desktop.
Save maedoc/3ec2d287b5d7cf8b07939a09b2183b37 to your computer and use it in GitHub Desktop.
(Mostly) fix format strings for Py 3.6 to % substitutions
import re
def lines(fname='awssg.py'):
with open(fname,'r') as fd:
for line in fd.readlines():
if "f'" in line:
yield line
def fmt_str(line):
ex = r'f\'(.*)\''
yield from re.finditer(ex, line)
def fix_line(l):
m, = fmt_str(l)
a, b, c = l[:m.start()], l[m.start()+2:m.end()-1], l[m.end():]
return a + fix_fstr(b) + c
def fix_fstr(ts):
nl = ''
i = 0
args = []
for m in re.finditer(r'{(.*?)}', ts):
nl = nl + ts[i:m.start()] + '%s'
i = m.end()
args.append(m.group()[1:-1])
nl = nl + ts[i:]
return '(%r %% (%s))' % (nl, ', '.join(args))
def fix_file(fname):
new_lines = []
with open(fname, 'r') as fd:
for line in fd.readlines():
if "f'" in line:
line = fix_line(line)
new_lines.append(line)
with open(fname, 'w') as fd:
for line in new_lines:
fd.write(line)
print('%d lines written' % (len(new_lines)))
@maedoc
Copy link
Author

maedoc commented Aug 20, 2017

Oops indented with \ts, oh well..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment