字符串格式化有两种方式:百分号方式、format方式。python
其中,百分号方式比较老,而format方式是比较先进的,企图替代古老的方式,目前二者共存。spa
格式:%[(name)][flags][width].[precision]typecodedebug
例子:code
>>> 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 用来作 debug 比较好,由于它会显示变量的原始数据(raw data),而其它的符号则是用来向用户显示输出的。
orm
>>> 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) # 能够看见与上面输出存在明显的区别
>>> 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'