Python中%r和%s的区别

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

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

 

函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。

 

有些情况下,两者处理的结果是一样的,比如说处理int型对象。

例一:

1

2

3

print "I am %d years old." % 22

print "I am %s years old." % 22

print "I am %r years old." % 22

 

返回结果:

1

2

3

I am 22 years old.

I am 22 years old.

I am 22 years old.

 

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

例二:

1

2

3

text = "I am %d years old." % 22

print "I said: %s." % text

print "I said: %r." % text

 

返回结果:

1

2

I said: I am 22 years old..

I said: 'I am 22 years old.'.   #%r 给字符串加了单引号

 

再看一种情况

例三:

1

2

3

4

import datetime

d = datetime.date.today()

print "%s" % d

print "%r" % d

 

返回结果:

1

2

2017-08-16

datetime.date(2017, 8, 16)

 

可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

LHStudio感谢您的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值