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编程在flask中模拟进行Restful的CRUD操作

Python编程在flask中模拟进行Restful的CRUD操作

这篇文章中我们将通过对HelloWorld的message进行操作,介绍一下如何使用flask进行Restful的CRUD。 概要信息 事前准备:flask liumiaocn:f...

Python subprocess模块学习总结

一、subprocess以及常用的封装函数运行python的时候,我们都是在创建并运行一个进程。像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。...

python引用(import)某个模块提示没找到对应模块的解决方法

python引用(import)某个模块提示没找到对应模块的解决方法

自己检查了很多遍,自己写的每错,但是还是报没有找到对应python模块。目录结构如下图所示: __init__.py这个文件需要引入models下的todo_kanban.py文件。_...

使用python在本地电脑上快速处理数据

大数据一般是在“云”上玩的,但“云”都是要钱的,而且数据上上下下的也比较麻烦。所以,在本地电脑上快速处理数据的技能还是要的。 pandas 在比赛中学到的一个工具,本地可以在亿级别的数据...

Python数据类型之列表和元组的方法实例详解

Python数据类型之列表和元组的方法实例详解

引言 我们前面的文章介绍了数字和字符串,比如我计算今天一天的开销花了多少钱我可以用数字来表示,如果是整形用 int ,如果是小数用 float ,如果你想记录某件东西花了多少钱,应该使用...