在Python中,编写以下代码很乏味:

print "foo is" + bar + '.'

我可以在Python中执行类似的操作吗?

print "foo is #{bar}."

推荐答案

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

Ruby相关问答推荐

为什么数组中的 splat 如此昂贵?

有人可以解释 Ruby 在块中使用管道字符吗?

Kernel#gets try 读取文件而不是标准输入

Ruby 对象打印为指针

如何将哈希保存到 CSV

Ruby - net/http - 重定向

判断字符串是否包含Ruby数组中的任何子字符串

如何用 Ruby 覆盖 shell 中的打印行?

判断 Ruby HTTP 响应是否成功

Ruby 中的 -> (stab) 运算符是什么?

如何将值保存到 YAML 文件中?

将数组分成 n 组 m 大小?

. vs ::(点与双冒号)用于调用方法

如何在课堂上使用 Enumerable mixin?

是什么让 Ruby 变慢了?

如何使用 RVM 更新 Ruby 解释器?

Ruby NOT Rails 中有复数函数吗?

错误数量的参数(1 代表 0)在 Ruby 中是什么意思?

如何在 Ruby 中获取堆栈跟踪对象?

使用整数作为哈希键