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

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

提交回复
热议问题