python中%r和%s的区别

枫铃3年前 (2021-10-03)Python221

%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.  

另外一些情况两者就不同了

例二:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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(2020, 1, 1, 1, 17, 34, 925488)
>> type(timeinfo)
datetime.datetime

>> repr(timeinfo)
'datetime.datetime(2020, 1, 1, 1, 17, 34, 925488)'
>> str(timeinfo)
'2020-01-01 01: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."
 ))

#输出:
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学习交流QQ群:531509025,群里有大量基础入门知识,都是从零开始的,群里还有专业的人给你解答问题。寻找有志同道合的小伙伴,互帮互助,群里还有不错PDF电子书!

相关文章

Python-functools (reduce,偏函数partial,lru_cache)

1、functools模块—reduce() reduce方法: reduce方法,就是减少 可迭代对象不能为空࿰...

Python 循环中的陷阱

Python 中的 fo...

python struct模块的使用

struct模块中的函数...

Python读写CSV文件

CSV(Comma-Se...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。