i’m trying to do some “post”/”lazy” evaluation of arguments on my strings. Suppose i’ve this:
s = "SELECT * FROM {table_name} WHERE {condition}"
I’d like to return the string with the {table_name} replaced, but not the {condition}, so, something like this:
s1 = s.format(table_name = "users")
So, I can build the hole string later, like:
final = s1.format(condition= "user.id = {id}".format(id=2))
The result should be, of course:
"SELECT * FROM users WHERE user.id = 2"
I’ve found this previous answer, this is exactly what I need, but i’d like to use the format string function.
python, format string
Thank you for your help!
You can’t use the format function because it will raise a KeyError.
string.Templatesupports safe substituion:If you use plain variable names (no format specifiers, no indexing, etc..) this will also work (thanks @Simeon Visser for the idea):