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

 
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')
 
Output
two one
 
 
Setup
data = {'first': 'Hodor', 'last': 'Hodor!'}



Old

'%(first)s %(last)s' % data


New

'{first} {last}'.format(**data)


Output

Hodor Hodor!
 
 
 
  • 從format參數引入的變量名 、
 
  • 冒號:、字符位數聲明、空白自動填補符 的聲明、千分位的聲明、變量類型的聲明: 字符串s、數字d、浮點數f 、對齊方向符號 < ^ >
'{:.5}'.format('xylophone')


Output

xylop
        
'{:^10}'.format('test')


Output

   test   
 
'{:.{}}'.format('xylophone', 7)


Output

xylopho
'{:4d}'.format(42)


Output

  42
'{:06.2f}'.format(3.141592653589793)


Output

003.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)


Output

23 42
 

Setup

class Plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]


New

'{p.type}: {p.kinds[0][name]}'.format(p=Plant())


Output

tree: 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())


Output

str 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())


Output

I'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))


Output

2001-02-03 04:05
 
 
 
 
 
相關文章
相關標籤/搜索