Python the Hard Way - exercise 6 - %r versus %s

前端 未结 7 683
孤城傲影
孤城傲影 2020-12-04 17:35

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

Zed seems to use %r and %s interchangeably here, is there any difference between the two? Wh

相关标签:
7条回答
  • 2020-12-04 18:13

    The following is a summary of the preceding three code examples.

    # 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
    
    0 讨论(0)
  • 2020-12-04 18:13

    %s invokes str(), whereas %r invokes repr(). For details, see Difference between __str__ and __repr__ in Python

    0 讨论(0)
  • 2020-12-04 18:25
     x = "example"
     print "My %s"%x
    
           My example
    
     print "My %r"%x
    
           My 'example'
    

    It is well explained in the above answers. I have tried to show the same with a simple example.

    0 讨论(0)
  • 2020-12-04 18:27

    The code below illustrates the difference. Same value prints differently:

    x = "xxx"
    withR = "prints with quotes %r"
    withS = "prints without quotes %s"
    
    0 讨论(0)
  • 2020-12-04 18:35

    %r calls repr, while %s calls str. These may behave differently for some types, but not for others: repr returns "a printable representation of an object", while str returns "a nicely printable representation of an object". For example, they are different for strings:

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

    In this case, the repr is the literal representation of a string (which the Python interpreter can parse into a str object), while the str is just the contents of the string.

    0 讨论(0)
  • 2020-12-04 18:35

    %s => string

    %r => exactly as is

    Using the code in the book:

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

    we get

    Let's talk about Zed A. Shaw.
    Let's talk about 'Zed A. Shaw'.
    
    0 讨论(0)
提交回复
热议问题