How do I use Python to easily expand variables to strings?

前端 未结 4 1183
一个人的身影
一个人的身影 2021-02-05 07:52

What\'s a nice idiom to do this:

Instead of: print \"%s is a %s %s that %s\" % (name, adjective, noun, verb)

I want to be able to do something to th

4条回答
  •  你的背包
    2021-02-05 08:26

    "{name} is a {adjective} {noun} that {verb}".format(**locals())
    
    • locals() gives a reference to the current namespace (as a dictionary).
    • **locals() unpacks that dictionary into keyword arguments (f(**{'a': 0, 'b': 1}) is f(a=0, b=1)).
    • .format() is "the new string formatting", which can by the way do a lot more (e.g. {0.name} for the name attribute of the first positional argument).

    Alternatively, string.template (again, with locals if you want to avoid a redundant {'name': name, ...} dict literal).

提交回复
热议问题