Python是否在Ruby中执行类似于"string#{var}"的变量插值?

mko*_*mko 34 ruby python language-comparisons string-formatting string-interpolation

在Python中,编写它是很繁琐的:

print "foo is" + bar + '.'
Run Code Online (Sandbox Code Playgroud)

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

print "foo is #{bar}."

Sea*_*ira 50

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

f"foo is {bar}"
Run Code Online (Sandbox Code Playgroud)

对于此下面的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})
Run Code Online (Sandbox Code Playgroud)

  • 还有,对于懒惰,'print'foo是%(bar)s"%locals()`. (10认同)

AXO*_*AXO 25

Python 3.6 会的文字串插使用F-字符串:

print(f"foo is {bar}.")
Run Code Online (Sandbox Code Playgroud)

  • 如果有人想知道:是的,你可以将它与原始字符串结合起来,就像这样`rf"foo是{bar}"`. (2认同)

war*_*iuc 11

Python 3.6 引入了f-strings:

print(f"foo is {bar}.")
Run Code Online (Sandbox Code Playgroud)

老答案:

从版本3.2开始,Python str.format_map与其一起locals()globals()允许您快速执行:

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
>>> bar = "something"
>>> print("foo is {bar}".format_map(locals()))
foo is something
>>> 
Run Code Online (Sandbox Code Playgroud)


dki*_*kim 8

我从Python Essential Reference学到了以下技术:

>>> bar = "baz"
>>> print "foo is {bar}.".format(**vars())
foo is baz.
Run Code Online (Sandbox Code Playgroud)

当我们想要在格式化字符串中引用许多变量时,这非常有用:

  • 我们不必再次重复参数列表中的所有变量:将它与基于显式关键字参数的方法(例如"{x}{y}".format(x=x, y=y)"%(x)%(y)" % {"x": x, "y": y})进行比较.
  • 如果参数列表中的变量顺序与格式化字符串中的顺序一致,我们不必逐个检查:将其与基于位置参数的方法(例如"{}{}".format(x, y),"{0}{1}".format(x, y)"%s%s" % (x, y))进行比较.

  • 这是一个奇怪的传递方式......虽然非常整洁,但却更接近Ruby方式. (2认同)

Jos*_*iah 5

字符串格式

>>> bar = 1
>>> print "foo is {}.".format(bar)
foo is 1.
Run Code Online (Sandbox Code Playgroud)

  • 或更旧但仍很流行:打印“ foo is%s”%str(bar) (3认同)