python %r %s %d 用法和区别

%可以理解为就是一个占位符。
python中用%代表格式符,表示格式化操作,常用的操作有%s,%d,%r等.
%r用rper()方法处理对象
%s用str()方法处理对象
%d十进制整数表示

#!/usr/local/python/bin/python
# -*-coding=utf8 -*-

x = "weiruoyu"
y = 25.66

print "%s" %x
print "%s" %y
print "=========="

print "%r" %x
print "%r" %y

print "=========="
print "%d" %y
print "%d" %x

输出结果:

weiruoyu
25.66
==========
'weiruoyu'
25.66
==========
25
Traceback (most recent call last):
  File "/tmp/testpy/tmp.py", line 17, in ?
    print "%d" %x
TypeError: int argument required

Process finished with exit code 1

%d不能读取字符串,删除最后一行就可以了。输出结果如下:

weiruoyu
25.66
==========
'weiruoyu'
25.66
==========
25

下面案例还是有一些小区别:

>>> import datetime
>>> d = datetime.date.today()
>>> print '%s' % d
2018-11-22
>>> print '%r' % d 
datetime.date(2018, 11, 22)

猜你喜欢

转载自blog.51cto.com/weiruoyu/2320781