字符串格式化有两种方式:百分号方式、format方式。
其中,百分号方式比较老,而format方式是比较先进的,企图替代古老的方式,目前两者共存。
1.百分号方式
格式:%[(name)][flags][width].[precision]typecode
(name) 可选,用于选择指定的key
flags 可选,可供选择的值有:
+ 右对齐:正数的加正号,负数的加负号
- 左对齐:正数前没有负号,负数前加负号
width 可选,占有宽度
.precision 可选,小数点后保留的位数
typecode 必选
s,获取传入的对象__str__方法的返回值,并将其格式化到指定位置
r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
c,整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <=1114111
o,将整数转换成八进制表示,并将其格式化到指定位置
x,将整数转换成16进制,并将其格式化到指定位置
d,将整数,浮点数转化为十进制表示,并将其格式化到指定位置
例子:
>>> s = 'hello, %s!' % 'python'
>>> s
'hello, python!'
>>> s = 'hello, %s, %d!' % ('python', 2018)
>>> s
'hello, python, 2018!'
>>> s = 'hello, %(name)s, %(year)d!' % {'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018!'
>>> s = 'hello, %(name)+10s, %(year)-10d!' % {'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018 !'
>>> s = 'hello, %(name)s, %(year).3f!' % {'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018.000!'
%r 与 %s 区别:
%r 用来做 debug 比较好,因为它会显示变量的原始数据(raw data),而其它的符号则是用来向用户显示输出的。
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> a = 'sunday'
>>> print("Today is %s" % a)
Today is sunday
>>> print("Today is %r" % a)
Today is 'sunday' # 格式化部分用单引号输出
>>> from datetime import datetime
>>> d = datetime.now()
>>> print('%s' % d)
2018-09-10 08:52:00.769949
>>> print('%r' % d)
datetime.datetime(2018, 9, 10, 8, 52, 0, 769949) # 可以看见与上面输出存在明显的区别
2.format方式
>>> s = 'hello, {}, {}'.format('python', 2018)
>>> s
'hello, python, 2018'
>>> s = 'hello, {0}, {1}, hi, {0}'.format('python', 2018)
>>> s
'hello, python, 2018, hi, python'
>>> s = 'hello, {name}, {year}, hi, {name}'.format(name='python', year=2018)
>>> s
'hello, python, 2018, hi, python'
>>> s = 'hello, {:s}, {:d}, hi, {:f}'.format('python', 2018, 9.7)
>>> s
'hello, python, 2018, hi, 9.700000'