如何使用Python轻松将变量扩展为字符串? [英] How do I use Python to easily expand variables to strings?

查看:114
本文介绍了如何使用Python轻松将变量扩展为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做有什么好习惯?

代替: print "%s is a %s %s that %s" % (name, adjective, noun, verb)

我希望能够做到以下几点: print "{name} is a {adjective} {noun} that {verb}"

I want to be able to do something to the effect of: print "{name} is a {adjective} {noun} that {verb}"

推荐答案

"{name} is a {adjective} {noun} that {verb}".format(**locals())

  • locals()提供对当前名称空间的引用(作为字典).
  • **locals()将该字典解压缩为关键字参数(f(**{'a': 0, 'b': 1})f(a=0, b=1)).
  • .format()新字符串格式" ,它可以顺便说一句,可以做更多的事情(例如,第一个位置参数的name属性的{0.name}).
    • 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).
    • 或者, string.template (同样,如果您是本地人,想要避免多余的{'name': name, ...} dict文字).

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

      这篇关于如何使用Python轻松将变量扩展为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆