Python中%r和%s的详解及区别

yipeiwu_com6年前Python基础

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 给字符串加了单引号 

再看一种情况

例三:

import datetime 
d = datetime.date.today() 
print "%s" % d 
print "%r" % d 

返回结果:

2014-04-14 
datetime.date(2014, 4, 14) 

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python实现全局变量的两个解决方法

本文针对Python的全局变量实现方法简述如下: 先来看下面一段测试程序: count = 0 def Fuc(count): print count count += 1...

python通过ssh-powershell监控windows的方法

本文实例讲述了python通过ssh-powershell监控windows的方法。分享给大家供大家参考。具体分析如下: 对于服务器的监控来说,监控linux不管是自己动手写脚本还是用一...

python之mock模块基本使用方法详解

mock简介 mock原是python的第三方库 python3以后mock模块已经整合到了unittest测试框架中,不用再单独安装 Mock这个词在英语中有模拟的意思,因此我们可以...

python中scikit-learn机器代码实例

我们给大家带来了关于学习python中scikit-learn机器代码的相关具体实例,以下就是全部代码内容: # -*- coding: utf-8 -*- import num...

Python eval的常见错误封装及利用原理详解

最近在代码评审的过程,发现挺多错误使用eval导致代码注入的问题,比较典型的就是把eval当解析dict使用,有的就是简单的使用eval,有的就是错误的封装了eval,供全产品使用,这引...