Last active
July 11, 2019 17:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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