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小白必备的8个最常用的内置函数(推荐)

Python给我们内置了大量功能函数,官方文档上列出了69个,有些是我们是平时开发中经常遇到的,也有一些函数很少被用到,这里列举被开发者使用最频繁的8个函数以及他们的详细用法 print...

pandas数据处理进阶详解

一、pandas的统计分析 1、关于pandas 的数值统计(统计detail 中的 单价的相关指标) import pandas as pd # 加载数据 detail =...

Python 私有化操作实例分析

Python 私有化操作实例分析

本文实例讲述了Python 私有化操作。分享给大家供大家参考,具体如下: 私有化 xx: 公有变量 _x: 单前置下划线,私有化属性或方法,from somemodule import...

python判断文件是否存在,不存在就创建一个的实例

如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f = open("D:/1.txt",'w')...

在Python中pandas.DataFrame重置索引名称的实例

例子: 创建DataFrame ### 导入模块 import numpy as np import pandas as pd import matplotlib.pyplot as...