python中%r和%s的区别

Posted xushukui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中%r和%s的区别相关的知识,希望对你有一定的参考价值。

%r用rper()方法处理对象

%s用str()方法处理对象

有些情况下,两者处理的结果是一样的,比如说处理int型对象。
例一:
print "I am %d years old." % 22  
print "I am %s years old." % 22  
print "I am %r years old." % 22  

I am 22 years old.  
I am 22 years old.  
I am 22 years old.  

另外一些情况两者就不同了
例二:
text = "I am %d years old." % 22  
print "I said: %s." % text  
print "I said: %r." % text  

返回结果:
I said: I am 22 years old..  
I said: ‘I am 22 years old.‘. // %r 给字符串加了单引号  

再看一种情况
例三:
>> from datetime import datetime 
>> timeinfo = datetime.today()

>> timeinfo
datetime.datetime(2016, 6, 7, 21, 17, 34, 925488)
>> type(timeinfo)
datetime.datetime

>> repr(timeinfo)
‘datetime.datetime(2016, 6, 7, 21, 17, 34, 925488)‘
>> str(timeinfo)
‘2016-06-07 21:17:34.925488‘

%r会将后面给的参数原样打印出来,带有类型信息。
formatter = "%r %r %r %r"
 
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
 "But it didn‘t sing.",
 "So I said goodnight."
 )

输出结果:

$ python ex8.py
1 2 3 4
‘one‘ ‘two‘ ‘three‘ ‘four‘
True False False True
‘%r %r %r %r‘ %r %r %r %r %r %r %r %r %r %r %r %r
‘I had this thing.‘ ‘That you could type up right.‘ "But it didn‘t sing." ‘So I said goodnight.‘
$

以上是关于python中%r和%s的区别的主要内容,如果未能解决你的问题,请参考以下文章

python %r %s %d 用法和区别

python 和 r 的区别 知乎

Python snippet(代码片段)

关于代码片段的时间复杂度

Python 中的 !r 和 %r 有啥区别?

在 Python 格式(f-string)字符串中,!r 是啥意思? [复制]