Python 是否做类似于“string #{var}"的变量插值?在红宝石? [英] Does Python do variable interpolation similar to "string #{var}" in Ruby?

查看:41
本文介绍了Python 是否做类似于“string #{var}"的变量插值?在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,写起来很乏味:

In Python, it is tedious to write:

print "foo is" + bar + '.'

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

Can I do something like this in Python?

打印foo is #{bar}."

推荐答案

Python 3.6+ 确实有变量插值 - 在字符串前添加 f :

Python 3.6+ does have variable interpolation - prepend an f to your string:

f"foo is {bar}"

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

For versions of Python below this (Python 2 - 3.5) you can use str.format to pass in variables:

# 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})

这篇关于Python 是否做类似于“string #{var}"的变量插值?在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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