'passing python parameters into a string which will be used as a python parameter
I am trying to pass python from a string in a web form with other inputs as optional parameters. I am using flask and all the values arrive at a python program as strings. I would like to do something like this. I suspect the whole idea is impossible :)
Any ideas Stack ??
parameter_1 = "Foo"
parameter_2 = "Bar"
sql_string = 'Hello {parameter_1} this is {parameter_2}; '
formatted_sql = f'''{sql_string}'''
print(sql_string)
print(formatted_sql)
Solution 1:[1]
You can use .format():
parameter_1 = "Foo"
parameter_2 = "Bar"
sql_string = 'Hello {p1} this is {p2}'
formatted = sql_string.format(p1=parameter_1, p2=parameter_2)
print(sql_string)
print(formatted)
This also allows sql_string to be used repeatedly, with different parameters.
Solution 2:[2]
Python is quite.. dynamic. You can use locals() to get a dict of the local variables. Then use str.format() to apply to the template (it will not be a f-string):
parameter_1 = "Foo"
parameter_2 = "Bar"
sql_string = 'Hello {parameter_1} this is {parameter_2}; '
formatted_sql = sql_string.format(**locals())
print(sql_string)
print(formatted_sql)
This will output:
Hello {parameter_1} this is {parameter_2};
Hello Foo this is Bar;
Now.. it WOULD be a better idea to just define the replacement variables directly as a dict such as:
tvars = { 'parameter_1': 'Foo', 'parameter_2': 'Bar' }
formatted_sql = sql_string.format(**tvars)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 2pichar |
| Solution 2 | vaizki |
