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

前端 未结 7 694
孤城傲影
孤城傲影 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
    

提交回复
热议问题