Python 是否会像 Ruby 中的“string #{var}”那样进行变量插值?

新手上路,请多包涵

在 Python 中,这样写是很乏味的:

 print "foo is" + bar + '.'

我可以在 Python 中做这样的事情吗?

print "foo is #{bar}."

原文由 mko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 428
2 个回答

Python 3.6+ 确实有变量插值 - 在你的字符串前加上 f

 f"foo is {bar}"

对于低于此版本的 Python (Python 2 - 3.5),您可以使用 str.format 传递变量:

 # Rather than this:
print("foo is #{bar}")

# You would do this:
print("foo is {}".format(bar))

# Or this:
print("foo is {bar}".format(bar=bar))

# Or this:
print("foo is %s" % (bar, ))

# Or even this:
print("foo is %(bar)s" % {"bar": bar})

原文由 Sean Vieira 发布,翻译遵循 CC BY-SA 4.0 许可协议

Python 3.6会有使用 f-strings 进行 文字字符串插值

 print(f"foo is {bar}.")

原文由 AXO 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏