stackoverflow 收藏

What is the difference between !r and %r in Python?

链接
答案:

  • str.format() will call the object.__format__() method on the object itself, but by using !r, repr(object).__format__() is used instead.
  • '{}'.format() 相当于 object.__format()__
  • '{!r}'.format() 相当于 repr(object).__format__()
  • 官方文档-input_and_output
    • The str() function is meant to return representations of values which are fairly human-readable, while repr()is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax).