Last active
September 13, 2019 18:46
-
-
Save scwood/610af35b98db6e19ea6e1c02bd295b8e to your computer and use it in GitHub Desktop.
Variable expansion
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
| # 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