【问题标题】:Does Python do variable interpolation similar to "string #{var}" in Ruby?Python 是否在 Ruby 中进行类似于“字符串#{var}”的变量插值?
【发布时间】:2012-08-01 01:46:55
【问题描述】:

在Python中,写起来很乏味:

print "foo is" + bar + '.'

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

print "foo is #{bar}."

【问题讨论】:

标签: python ruby string-formatting string-interpolation language-comparisons


【解决方案1】:

是的,当然。在我看来,Python 对字符串格式化、替换和运算符有很好的支持。

这可能会有所帮助:
http://docs.python.org/library/stdtypes.html#string-formatting-operations

【讨论】:

    【解决方案2】:

    String formatting

    >>> bar = 1
    >>> print "foo is {}.".format(bar)
    foo is 1.
    

    【讨论】:

    • 或更旧但仍然流行:print "foo is %s" % str(bar)
    • 现在应该已经弃用了,虽然我找不到 PEP。
    • 不被弃用,只是被取代。
    • I guess in Python 2 it's not,但至少应该在前一段时间发布的 3.1 中弃用它。
    【解决方案3】:

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

    【讨论】:

    • 第三个看起来很整洁,但我记得这种方式有点过时了?这是真的吗?
    • 对于懒惰的人来说,还有print "foo is %(bar)s" % locals()
    • @yozloy - 更正它在 Python 3 中已被弃用(据我所知)。
    • Python 3 中不再不推荐使用 % 语法:stackoverflow.com/a/23381153/770425
    • 这是不正确的,因为3.6 introduced f-strings
    【解决方案4】:

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

    >>> bar = "baz"
    >>> print "foo is {bar}.".format(**vars())
    foo is baz.
    

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

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

    【讨论】:

    • 这是一种...奇怪的方式通过酒吧...虽然很整洁,使它更接近 Ruby 方式。
    • 如果您使用的是对象,这似乎是最好的解决方案。例如,如果您要报告 urllib2.HTTPError,您可以执行 "HTTP error: {error.code} {error.msg}".format(**vars()) 这不适用于 format(**locals())
    【解决方案5】:

    我更喜欢这种方法,因为您不必重复引用变量两次:

    阿尔法 = 123 print '答案是 {alpha}'.format(**locals())

    【讨论】:

    • 但我想这很慢 - 为参数解压缩一个可能很大的字典。
    • @warwaruk 写入标准输出是限制因素,打印字符串比格式化它需要 10 倍的时间,此外 locals() 返回一个引用,所以我认为这种方法非常快
    【解决方案6】:

    这在 Ruby 中有很大的不同:

    print "foo is #{bar}."
    

    还有这些在 Python 中:

    print "foo is {bar}".format(bar=bar)
    

    在 Ruby 示例中,bar评估
    在 Python 示例中,bar 只是字典的键

    如果您只是使用变量,则其行为或多或少是相同的,但总的来说,将 Ruby 转换为 Python 并不是那么简单

    【讨论】:

    • 自 3.6 以来这是不正确的。我们现在有print(f"foo is #{bar}")
    【解决方案7】:

    Python 3.6 有introduced f-strings:

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

    旧答案:

    自 3.2 版以来,Python 有 str.format_maplocals()globals() 一起让你做的更快:

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

    【讨论】:

      【解决方案8】:

      Python 3.6 将拥有使用 f-strings 拥有literal string interpolation

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

      【讨论】:

      • 如果有人想知道:是的,您可以将它与原始字符串结合起来,例如 rf"foo is {bar}"
      【解决方案9】:

      几乎所有其他答案都不适合我。可能是因为我在 Python3.5 上。唯一有效的是:

       print("Foobar is %s%s" %('Foo','bar',))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-08
        • 2016-05-02
        • 2011-12-06
        • 2011-05-25
        • 2015-05-24
        • 2020-04-02
        • 1970-01-01
        • 2016-03-29
        相关资源
        最近更新 更多