Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active September 13, 2019 18:46
Show Gist options
  • Select an option

  • Save scwood/610af35b98db6e19ea6e1c02bd295b8e to your computer and use it in GitHub Desktop.

Select an option

Save scwood/610af35b98db6e19ea6e1c02bd295b8e to your computer and use it in GitHub Desktop.
Variable expansion
# Another idea, you could avoid any "custom language" / parsing / regex stuff by just referencing
# variables by ID an having them provide valid python strings that have format placeholders
# documentation on the string.format function: https://www.geeksforgeeks.org/python-format-function/
json = {
'variables': {
'foo': 'asdf',
'bar': 'fdsa'
},
'expressions': [
{
'text': 'my cool string {}, it has variables {}'
'variables': ['foo', 'bar']
]
}
for expression in json["expressions"]:
# first get the value for each of the variables in the expression
# (in your real script you'll obviously need to do this more dynamically
variable_values = [
json['variables'][expression['variables'][0]],
json['variables'][expression['variables'][1]]
]
# then provide them as argument to the format function and you're good to go
replaced_text = expression['text'].format(*variable_values)
# 'my cool string asdf, it has variables fdsa'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment