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)

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

相关文章

对web.py设置favicon.ico的方法详解

本文介绍在web.py中设置favicon.ico的方法: 如果没设置favicon,后台日志是这样的: 127.0.0.1:4133 - - [03/Sep/2015 18:49:...

python 并发编程 非阻塞IO模型原理解析

python 并发编程 非阻塞IO模型原理解析

非阻塞IO(non-blocking IO) Linux下,可以通过设置socket使其变为non-blocking。当对一个non-blocking socket执行读操作时,流程是...

python Qt5实现窗体跟踪鼠标移动

我就废话不多说了, 直接上代码吧! from PyQt5.Qt import * import sys class Window(QWidget): def __init...

Python WEB应用部署的实现方法

Python WEB应用部署的实现方法

本文介绍了Python WEB应用部署的实现方法,分享给大家,具体如下: 使用Apache模块mod_wsgi运行Python WSGI应用 Flask应用是基于WSGI规范的,所以...

Python2.x版本中cmp()方法的使用教程

 cmp()方法返回两个数的差的符号: -1 如果 x < y, 0 如果 x == y, 或者 1 如果 x > y . 语法 以下是cmp()方法的语法:...