【问题标题】:What does % do to strings in Python?% 对 Python 中的字符串有什么作用?
【发布时间】:2010-11-17 07:42:48
【问题描述】:

我找不到运算符 % 的文档,因为它在 Python 中用于字符串。这个运算符和左边的字符串一起使用时会做什么?

【问题讨论】:

  • 我没有看到任何要求在这个问题中查找任何场外资源的请求。 OP表示是因为找不到站外资源才来的。这就像请求异地资源的相反。如果像这样直接简单的编程问题是题外话,什么是允许的?

标签: python string documentation operators


【解决方案1】:

是字符串格式化操作符。阅读string formatting in Python

format % values

创建一个字符串,其中format 指定格式,values 是要填写的值。

【讨论】:

    【解决方案2】:

    注意,从 Python 2.6 开始,建议使用新的str.format() 方法:

    >>> "The sum of 1 + 2 is {0}".format(1+2)
    'The sum of 1 + 2 is 3'
    

    如果您使用的是 2.6,您可能希望继续使用 % 以保持与旧版本的兼容性,但在 Python 3 中没有理由不使用 str.format()

    【讨论】:

    • format() 也非常强大。您可以使用命名标签,例如“Hello {planet}”.format(planet='earth')
    • {} 中的 0 有什么作用?没有它,这行代码似乎运行相同
    【解决方案3】:

    它将printf-like formatting 应用于字符串,以便您可以用变量值替换字符串的某些部分。 示例

    # assuming numFiles is an int variable
    print "Found %d files" % (numFiles, )
    

    查看 Konrad 提供的链接

    【讨论】:

      【解决方案4】:

      '%' 运算符用于字符串插值。从 Python 2.6 开始,使用 insted 字符串方法“format”。详情见http://www.python.org/dev/peps/pep-3101/

      【讨论】:

        猜你喜欢
        • 2020-02-15
        • 2011-09-02
        • 1970-01-01
        • 2016-09-23
        • 2021-12-16
        • 1970-01-01
        • 2010-09-13
        相关资源
        最近更新 更多