Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save orientalperil/8c1abc94204053f23f849e63cef50fce to your computer and use it in GitHub Desktop.

Select an option

Save orientalperil/8c1abc94204053f23f849e63cef50fce to your computer and use it in GitHub Desktop.
Convert ES6 string formatting to sprintf()
def find_string_formatting(text):
first = text.find('`')
second = text.find('`', first+1)
match = text[first:second+1]
match = match[1:len(match)-1]
vars = []
format_string = match
while '${' in format_string:
var = find_var(format_string)
vars.append(var)
format_string = format_string.replace('${{{}}}'.format(var), '%s')
new = "s.sprintf('{}', {})".format(format_string, ', '.join(vars))
return '`{}`'.format(match), new
def find_var(text):
first = text.find('${')
second = text.find('}')
match = text[first:second+1]
return match.replace('${', '').replace('}', '')
def main(text):
while '`' in text:
old, new = find_string_formatting(text)
text = text.replace(old, new)
return text
print main('`#${scopeSelector} .grid-row input[data-day=${day}]`')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment