Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active July 11, 2019 17:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyseek/7800650 to your computer and use it in GitHub Desktop.
Save tonyseek/7800650 to your computer and use it in GitHub Desktop.
Convert the old style string formatting of Python into the new style one.
import re
def convert_string_template(string):
index = -1
def repl(matched):
nonlocal index
keyword = matched.group(1)
if keyword:
return "{%s}" % keyword.strip('()')
else:
index += 1
return "{%d}" % index
return re.sub(r'(?:%(\(\w+\))?[diouxXeEfFgGcrs])', repl, string)
assert convert_string_template("%s %d %(a)s %(b)d %d") == '{0} {1} {a} {b} {2}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment