python中%r和%s的区别
2016-12-29 09:32
507 查看
%r用rper()方法处理对象
%s用str()方法处理对象
有些情况下,两者处理的结果是一样的,比如说处理int型对象。
例一:
[python] view
plain copy
print "I am %d years old." % 22
print "I am %s years old." % 22
print "I am %r years old." % 22
返回结果:
[python] view
plain copy
I am 22 years old.
I am 22 years old.
I am 22 years old.
另外一些情况两者就不同了
例二:
[python] view
plain copy
text = "I am %d years old." % 22
print "I said: %s." % text
print "I said: %r." % text
返回结果:
[python] view
plain copy
I said: I am 22 years old..
I said: 'I am 22 years old.'. // %r 给字符串加了单引号
再看一种情况
例三:
[python] view
plain copy
import datetime
d = datetime.date.today()
print "%s" % d
print "%r" % d
返回结果:
[python] view
plain copy
2014-04-14
datetime.date(2014, 4, 14)
可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)
参考:http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python
%s用str()方法处理对象
有些情况下,两者处理的结果是一样的,比如说处理int型对象。
例一:
[python] view
plain copy
print "I am %d years old." % 22
print "I am %s years old." % 22
print "I am %r years old." % 22
返回结果:
[python] view
plain copy
I am 22 years old.
I am 22 years old.
I am 22 years old.
另外一些情况两者就不同了
例二:
[python] view
plain copy
text = "I am %d years old." % 22
print "I said: %s." % text
print "I said: %r." % text
返回结果:
[python] view
plain copy
I said: I am 22 years old..
I said: 'I am 22 years old.'. // %r 给字符串加了单引号
再看一种情况
例三:
[python] view
plain copy
import datetime
d = datetime.date.today()
print "%s" % d
print "%r" % d
返回结果:
[python] view
plain copy
2014-04-14
datetime.date(2014, 4, 14)
可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)
参考:http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python
相关文章推荐
- python中%r和%s的区别
- python中%r和%s的区别
- python 中的%s 和%r的区别
- python中%r和%s的区别
- python中%s与%r的区别
- Python中%r和%s的区别
- python中%s与%r的区别
- Python %s和%r的区别
- python中%r和%s的区别
- python %r 和%s的区别
- Python 格式化输出 —— %r 与 %s 的区别(__repr__ 与 __str__)
- python学习笔记1:%r和%s的区别
- Python中%s和%r的区别
- Python 版本3和版本2 的字符串格式化区别 ----%s
- python3 开发面试题(%s和format的区别)5.31
- Python 格式化字符%r与%s的区别
- Python的ASCII, GB2312, Unicode , UTF-8区别
- python:单引号,双引号和三引号的区别
- %s 与 %ls的区别
- Python的ASCII, GB2312, Unicode , UTF-8区别