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

拜拜、爱过 提交于 2020-01-01 02:34:23

问题


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 the effect of: print "{name} is a {adjective} {noun} that {verb}"


回答1:


"{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).




回答2:


use string.Template

>>> from string import Template
>>> t = Template("$name is a $adjective $noun that $verb")
>>> t.substitute(name="Lionel", adjective="awesome", noun="dude", verb="snores")
'Lionel is a awesome dude that snores'



回答3:


For python 2 do:

print name,'is a',adjective,noun,'that',verb

For python 3 add parens:

print(name,'is a',adjective,noun,'that',verb)

If you need to save it to a string, you'll have to concatenate with the + operator and you'll have to insert spaces. print inserts a space at all the , unless there is a trailing comma at the end of the parameters, in which case it forgoes the newline.

To save to string var:

result = name+' is a '+adjective+' '+noun+' that '+verb


来源:https://stackoverflow.com/questions/4840580/how-do-i-use-python-to-easily-expand-variables-to-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!