码迷,mamicode.com
首页 > 编程语言 > 详细

python中%r和%s的区别

时间:2018-01-02 21:19:33      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:int   字符   oda   repr   import   类型   mat   pytho   print   

%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的区别

标签:int   字符   oda   repr   import   类型   mat   pytho   print   

原文地址:https://www.cnblogs.com/nyist-xsk/p/8178916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!