標籤:參數 ant python 3.1 ret 模式 引用 orm 格式
python從2.6開始支援format,新的更加容易讀懂的字串格式化方法,從原來的% 模式變成新的可讀性更強的
- 花括弧聲明{}、用於渲染前的參數引用聲明, 花括弧裡可以用數字代表引用參數的序號, 或者 變數名直接引用。
- 從format參數引入的變數名 、
- 冒號:、
- 字元位元聲明、
- 空白自動填補符 的聲明
- 千分位的聲明
- 變數類型的聲明: 字串s、數字d、浮點數f
- 對齊方向符號 < ^ >
- 屬性訪問符中括弧 ?
- 使用驚歎號!後接a 、r、 s,聲明 是使用何種模式, acsii模式、引用__repr__ 或 __str__
- 增加類魔法函數__format__(self, format) , 可以根據format前的字串格式來定製不同的顯示, 如: ’{:xxxx}’ 此時xxxx會作為參數傳入__format__函數中。
綜合舉例說明:
- 如: 千分位、浮點數、填充字元、對齊的組合使用:
輸入: ‘{:>18,.2f}‘.format(70305084.0) # :冒號+空白填充+靠右對齊+固定寬度18+浮點精度.2+浮點數聲明f輸出:‘ 70,305,084.00‘
- 複雜資料格式化
輸入: data = [4, 8, 15, 16, 23, 42] ‘{d[4]} {d[5]}‘.format(d=data)輸出: 23 42
- 複雜資料格式化:
輸入: class Plant(object):
type = ‘tree‘
kinds = [{‘name‘: ‘oak‘}, {‘name‘: ‘maple‘}]
‘{p.type}: {p.kinds[0][name]}‘.format(p=Plant())輸出:tree: oak 分類舉例說明:
- 花括弧聲明{}、用於渲染前的參數引用聲明, 花括弧裡可以用數字代表引用參數的序號, 或者 變數名直接引用。
‘{} {}‘.format(‘one‘, ‘two‘)‘{1} {0}‘.format(‘one‘, ‘two‘)
Outputtwo one Setup
data = {‘first‘: ‘Hodor‘, ‘last‘: ‘Hodor!‘}
Old
‘%(first)s %(last)s‘ % data
New
‘{first} {last}‘.format(**data)
OutputHodor Hodor!
- 冒號:、字元位元聲明、空白自動填補符 的聲明、千分位的聲明、變數類型的聲明: 字串s、數字d、浮點數f 、對齊方向符號 < ^ >
‘{:.5}‘.format(‘xylophone‘)
Outputxylop
‘{:^10}‘.format(‘test‘)
Output test
‘{:.{}}‘.format(‘xylophone‘, 7)
Outputxylopho
‘{:4d}‘.format(42)
Output 42
‘{:06.2f}‘.format(3.141592653589793)
Output003.14
‘{:+d}‘.format(42)
Output+42 千分位、浮點數、填充字元、對齊的組合使用: 輸入: ‘{:>18,.2f}‘.format(70305084.0) # :冒號+空白填充+靠右對齊+固定寬度18+浮點精度.2+浮點數聲明f輸出:‘ 70,305,084.00‘
Setup
person = {‘first‘: ‘Jean-Luc‘, ‘last‘: ‘Picard‘}
New
‘{p[first]} {p[last]}‘.format(p=person)
Output
Jean-Luc Picard
Setup
data = [4, 8, 15, 16, 23, 42]
New
‘{d[4]} {d[5]}‘.format(d=data)
Output23 42 Setup
class Plant(object): type = ‘tree‘ kinds = [{‘name‘: ‘oak‘}, {‘name‘: ‘maple‘}]
New
‘{p.type}: {p.kinds[0][name]}‘.format(p=Plant())
Outputtree: oak
Setup
class Data(object): def __str__(self): return ‘str‘ def __repr__(self): return ‘repr‘
Old
‘%s %r‘ % (Data(), Data())
New
‘{0!s} {0!r}‘.format(Data())
Outputstr repr
- 增加類魔法函數__format__(self, format) , 可以根據format前的字串格式來定製不同的顯示, 如: ’{:xxxx}’ 此時xxxx會作為參數傳入__format__函數中。
Setup
class HAL9000(object): def __format__(self, format): if (format == ‘open-the-pod-bay-doors‘): return "I‘m afraid I can‘t do that." return ‘HAL 9000‘
New
‘{:open-the-pod-bay-doors}‘.format(HAL9000())
OutputI‘m afraid I can‘t do that.
Setup
from datetime import datetime
New
‘{:%Y-%m-%d %H:%M}‘.format(datetime(2001, 2, 3, 4, 5))
Output2001-02-03 04:05
python字串格式化方法 format函數的使用