Python 字符串格式化輸出方式

字符串格式化有兩種方式:百分號方式、format方式。python

其中,百分號方式比較老,而format方式是比較先進的,企圖替代古老的方式,目前二者共存。spa

一、百分號方式

格式:%[(name)][flags][width].[precision]typecodedebug

  • (name)    可選,用於選擇指定的key
  • flags        可選,可供選擇的值有:
    • + 右對齊:正數的加正號,負數的加負號
    • - 左對齊:正數前沒有負號,負數前加負號
  • width    可選,佔有寬度
  • .precision    可選,小數點後保留的位數
  • typecode     必選
    • s,獲取傳入的對象__str__方法的返回值,並將其格式化到指定位置
    • r,獲取傳入對象的__repr__方法的返回值,並將其格式化到指定位置
    • c,整數:將數字轉換成其unicode對應的值,10進制範圍爲0 <= i <=1114111
    • o,將整數轉換成八進制表示,並將其格式化到指定位置
    • x,將整數轉換成16進制,並將其格式化到指定位置
    • d,將整數,浮點數轉化爲十進制表示,並將其格式化到指定位置

例子: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 與 %s 區別:

%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)  # 能夠看見與上面輸出存在明顯的區別

 二、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'
相關文章
相關標籤/搜索