字符串格式化有兩種方式:百分號方式、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'