何时在 Python 中使用 %r 而不是 %s? [英] When to use %r instead of %s in Python?

查看:58
本文介绍了何时在 Python 中使用 %r 而不是 %s?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Learn Python the Hard Way 第 21 页上,我看到了以下代码示例:

x = "有 %d 种人."% 10...打印我说:%r."% X

为什么在这里使用 %r 而不是 %s?什么时候用%r,什么时候用%s?

解决方案

%s 说明符使用 str()%r 使用 repr().

对于某些对象(例如整数),它们产生相同的结果,但是 repr() 的特殊之处在于(对于可能的类型)它通常返回一个有效的 Python 语法的结果,可用于明确地重新创建它所代表的对象.

这是一个使用日期的示例:

<预><代码>>>>导入日期时间>>>d = datetime.date.today()>>>字符串(d)'2011-05-14'>>>代表(d)'datetime.date(2011, 5, 14)'

repr() 不生成的类型Python 语法包括那些指向外部资源的语法,例如 file,您不能保证在不同的上下文中重新创建.

On Learn Python the Hard Way page 21, I see this code example:

x = "There are %d types of people." % 10
...
print "I said: %r." % x

Why is %r used here instead of %s? When would you use %r, and when would you use %s?

解决方案

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

这篇关于何时在 Python 中使用 %r 而不是 %s?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆