python字串格式化方法 format函數的使用

來源:互聯網
上載者:User

標籤:參數   ant   python   3.1   ret   模式   引用   orm   格式   

python從2.6開始支援format,新的更加容易讀懂的字串格式化方法,從原來的% 模式變成新的可讀性更強的
  1. 花括弧聲明{}、用於渲染前的參數引用聲明, 花括弧裡可以用數字代表引用參數的序號, 或者 變數名直接引用。
  2. 從format參數引入的變數名 、
  3. 冒號:、
  4. 字元位元聲明、
  5. 空白自動填補符 的聲明
  6. 千分位的聲明
  7. 變數類型的聲明: 字串s、數字d、浮點數f
  8. 對齊方向符號 < ^ >
  9. 屬性訪問符中括弧 ?
  10. 使用驚歎號!後接a 、r、 s,聲明 是使用何種模式, acsii模式、引用__repr__ 或 __str__
  11. 增加類魔法函數__format__(self, format) , 可以根據format前的字串格式來定製不同的顯示, 如: ’{:xxxx}’  此時xxxx會作為參數傳入__format__函數中。 
  綜合舉例說明:
  1. 如: 千分位、浮點數、填充字元、對齊的組合使用:
輸入: ‘{:>18,.2f}‘.format(70305084.0)     # :冒號+空白填充+靠右對齊+固定寬度18+浮點精度.2+浮點數聲明f輸出:‘     70,305,084.00‘ 
  1. 複雜資料格式化
輸入: data = [4, 8, 15, 16, 23, 42]            ‘{d[4]} {d[5]}‘.format(d=data)輸出: 23 42 
  1. 複雜資料格式化:
輸入: 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!   
  • 從format參數引入的變數名 、
 
  • 冒號:、字元位元聲明、空白自動填補符 的聲明、千分位的聲明、變數類型的聲明: 字串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  
  • 驚歎號!限定訪問__repr__等魔法函數:
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函數的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.