python中的%r、%s和%d有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15170349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:30:51  来源:igfitidea点击:

What's the difference between %r, %s and %d in python?

pythonstring

提问by mahr

Well, i just always use %r on python, but I don't know when I have to use these other formats...

好吧,我总是在 python 上使用 %r,但我不知道什么时候必须使用这些其他格式......

采纳答案by James Henstridge

This is explained in the Python documentation. In short,

这在Python 文档中进行解释。简而言之,

  • %dwill format a number for display.
  • %swill insert the presentation string representation of the object (i.e. str(o))
  • %rwill insert the canonical string representation of the object (i.e. repr(o))
  • %d将格式化一个数字以供显示。
  • %s将插入对象的表示字符串表示(即str(o)
  • %r将插入对象的规范字符串表示(即repr(o)

If you are formatting an integer, then these are equivalent. For most objects this is not the case.

如果您正在格式化一个整数,那么这些是等效的。对于大多数对象,情况并非如此。

回答by unutbu

Here is an example to supplement James Henstridge's answer:

以下是补充 James Henstridge 回答的示例:

class Cheese(float):
    def __str__(self):
        return 'Muenster'
    def __repr__(self):
        return 'Stilton'

chunk = Cheese(-123.4)

print(str(chunk))
# Muenster
print(repr(chunk))
# Stilton
print(int(chunk))
# -123
print('%s\t%r\t%d'%(chunk, chunk, chunk))
# Muenster  Stilton -123