在 Python 中,如果我想在打印时使用字符串中的变量,我会执行以下操作:
name = "newbie"
site = "Stack Overflow"
print("I, a %s, find %s very useful" % (name, site))
如果我想打印
"I, a newbie, find Stack Overflow to be very very very useful'
并用变量名替换 'very'
,我该怎么做,同时仍然使用 name
和 site
变量? 最佳答案
>>> print("I a {0} find {1} {2} {2} {2} {2} useful".format(name, site, 'very'))
I a newbie find stackoverflow very very very very useful
或者,使用名称:
>>> a='very'
>>> print("I a {name} find {site} {a} {a} {a} {a} useful".format(name=name, site=site, a=a))
I a newbie find stackoverflow very very very very useful
或者,使用本地字典:
>>> print("I a {name} find {site} {a} {a} {a} {a} useful".format(**locals()))
I a newbie find stackoverflow very very very very useful
关于python - 在打印中多次使用相同的变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29952423/