【问题标题】:Python the Hard Way - exercise 6 - %r versus %sPython the Hard Way - 练习 6 - %r 与 %s
【发布时间】:2012-02-17 15:52:01
【问题描述】:

http://learnpythonthehardway.org/book/ex6.html

Zed 在这里似乎可以互换使用%r%s,这两者有什么区别吗?为什么不一直使用%s

另外,我不确定要在文档中搜索什么才能找到有关此的更多信息。 %r%s 到底叫什么?格式化字符串?

【问题讨论】:

标签: python


【解决方案1】:

%r 调用repr,而%s 调用str。对于某些类型,它们的行为可能不同,但对于其他类型则不然:repr 返回“对象的可打印表示”,而str 返回“对象的很好 可打印表示”。例如,它们对于字符串是不同的:

>>> s = "spam"
>>> print(repr(s))
'spam'
>>> print(str(s))
spam

在这种情况下,repr 是字符串的文字表示形式(Python 解释器可以将其解析为 str 对象),而 str 只是字符串的内容。

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      他们被称为string formatting operations

      %s 和 %r 的区别在于 %s 使用 str 函数,而 %r 使用 repr 函数。您可以在this answer 中了解strrepr 之间的区别,但是对于内置类型,实践中最大的区别是repr 的字符串包含引号并且所有特殊字符都被转义。

      【讨论】:

        【解决方案4】:

        下面的代码说明了不同之处。相同的值打印不同:

        x = "xxx"
        withR = "prints with quotes %r"
        withS = "prints without quotes %s"
        

        【讨论】:

          【解决方案5】:
           x = "example"
           print "My %s"%x
          
                 My example
          
           print "My %r"%x
          
                 My 'example'
          

          上面的答案很好地解释了。我试图用一个简单的例子来证明这一点。

          【讨论】:

            【解决方案6】:

            以下是对前面三个代码示例的总结。

            # First Example
            s = 'spam'
            # "repr" returns a printable representation of an object,
            # which means the quote marks will also be printed.
            print(repr(s))
            # 'spam'
            # "str" returns a nicely printable representation of an
            # object, which means the quote marks are not included.
            print(str(s))
            # spam
            
            # Second Example.
            x = "example"
            print ("My %r" %x)
            # My 'example'
            # Note that the original double quotes now appear as single quotes.
            print ("My %s" %x)
            # My example
            
            # Third Example.
            x = 'xxx'
            withR = ("Prints with quotes: %r" %x)
            withS = ("Prints without quotes: %s" %x)
            print(withR)
            # Prints with quotes: 'xxx'
            print(withS)
            # Prints without quotes: xxx
            

            【讨论】:

              【解决方案7】:

              %s => 字符串

              %r => 完全一样

              使用书中的代码:

              my_name = 'Zed A. Shaw'
              print "Let's talk about %s." % my_name
              print "Let's talk about %r." % my_name
              

              我们得到

              Let's talk about Zed A. Shaw.
              Let's talk about 'Zed A. Shaw'.
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-05-25
                • 1970-01-01
                • 2012-08-20
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多