3.1.3 格式化字串的文法

來源:互聯網
上載者:User

標籤:milang   python   

字串str.format()和Formatter類都是使用相同的格式化字串。格式化字元使用大括弧{}來包含替換的欄位,任何不在大括弧裡的字元都是直接輸出而不作轉換。因此,想要輸出大括弧,就需要使用特別的方式,使用雙大括弧方式來輸出大括弧,比如{{來輸出{,}}來輸出}。

 

格式化字串的文法如下:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*

arg_name          ::=  [identifier | integer]

attribute_name    ::=  identifier

element_index     ::=  integer | index_string

index_string      ::=  <any source character except "]"> +

conversion        ::=  "r" | "s" | "a"

format_spec       ::=  <described in the next section>

 

3.1.3.1 格式字串說明串

 

格式字串說明串的文法如下:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill        ::=  <any character>

align       ::=  "<" | ">" | "=" | "^"

sign        ::=  "+" | "-" | " "

width       ::=  integer

precision   ::=  integer

type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

 

3.1.3.2 格式化字串的例子

下面例子主要採用新的格式化方式,而不是採用舊的%格式化方式。但在大多數情況下,新的格式文法與舊的文法是相似的。使用大括弧{}和分號:來代替百分比符號%。比如’%03.2f’就表示為’{:03.2f}’。不過,新的格式化方式也有些新選項和不同的使用方式,如下面的例子:

 

通過位置來訪問參數:

#string

 

import string

 

print(‘{0},{1},{2}‘.format(‘a‘, ‘b‘, ‘c‘))

print(‘{},{},{}‘.format(‘a‘, ‘b‘, ‘c‘))

print(‘{2},{1},{0}‘.format(‘a‘, ‘b‘, ‘c‘))

print(‘{2},{1},{0}‘.format(*‘abc‘))

print(‘{2},{1},{2}‘.format(‘abc‘, ‘123‘,‘888‘))

 

結果輸出如下:

a,b,c

a,b,c

c,b,a

c,b,a

888,123,888

在這個例子裡,語句‘{0},{1},{2}‘.format(‘a‘, ‘b‘, ‘c‘)中0,1,2是位置參數的序號,{0}就是說把參數‘a’在這個地方替換輸出,位置參數的序號是從0開始計數,從左向右依次增加。

在語句‘{},{},{}‘.format(‘a‘, ‘b‘, ‘c‘)裡,沒有指明位置參數,就按預設的位置進行輸出,如果大括弧的個數少於位置參數個數,那麼後面的參數就忽略輸出。在語句{2},{1},{0}‘.format(‘a‘, ‘b‘, ‘c‘)中,可以看到位置參數可以放在不同的輸出位置上,因而它的輸出就變成c字母先輸出,最後才是a輸出。在語句‘{2},{1},{0}‘.format(*‘abc‘)中,這裡主要使用參數列表化解析機制,在參數‘abc’前添加星號*,就是把參數先變成列表,再進行處理,列表中每一項的位置,就對應輸出時指明的位置參數,所以這語句的輸出還是c,b,a的順序。在語句‘{2},{1},{2}‘.format(‘abc‘, ‘123‘,‘888‘)中,主要說明了位置參數是可重複出現,也可以缺少一些位置參數。

 

通過名稱來訪問參數:

print(‘mouse:({x},{y})‘.format(x = ‘100‘, y = ‘200‘))

mousept = {‘x‘ : ‘200‘, ‘y‘ : ‘888‘}

print(‘mouse:({x},{y})‘.format(**mousept))

結果輸出如下:

mouse:(100,200)

mouse:(200,888)

在語句‘mouse:({x},{y})‘.format(x = ‘100‘, y = ‘200‘)中,並沒有發現前面位置參數的數字,而是使用名稱x,y取代了。當然在format參數裡需要採用關鍵字參數方式傳入,才可以把這些關鍵字參數與輸出的指定的名稱對應。在語句‘mouse:({x},{y})‘.format(**mousept)中,就直接使用了字典參數mousept進行傳入,然後使用兩個星號把字典參數反向解析為關鍵字參數傳入。

 

訪問參數的屬性:

print(‘複數的屬性訪問,實部={0.real} 虛部={0.imag}‘.format(3 + 4j))

class Point:

     def __init__(self, x, y):

         self.x, self.y = x, y

     def __str__(self):

         return ‘Point({self.x}, {self.y})‘.format(self = self)

print(str(Point(5,5)))

輸出結果如下:

複數的屬性訪問,實部=3.0 虛部=4.0

Point(5, 5)

在語句‘複數的屬性訪問,實部={0.real} 虛部={0.imag}‘.format(3 + 4j)中,格式化中直接存取複數的屬性,結果屬性可以直接在字串輸出。在語句‘Point({self.x}, {self.y})‘.format(self = self)中,可以直接存取類的屬性,結果把類屬性的值列印出來,這樣比在格式化函數裡再重新寫一遍屬性要要簡單很多,少輸入了不少字元。

 

訪問參數的項:

xy = (20, 30)

print(‘X軸:{0[0]}, Y軸:{0[1]}‘.format(xy))

輸出結果如下:

X軸:20, Y軸:30

通過這個例子裡可以看到在格式化中直接存取元組的項,比如0[0]表示訪問第一個參數的第一項,0[1]表示訪問第一個參數的第二項。

 

使用!s和!r來替換%s和%r:

print(‘repr() : {!r}; str() : {!s}‘.format(‘abc‘, ‘123‘))

輸出結果如下:

repr() : ‘abc‘; str() : 123

通過這個例子,就可以看到使用!s來替換%s,這樣更加簡單方便,同樣!r替換%r。

 

字串排列和寬度對齊

print(‘{:<30}‘.format(‘靠左對齊‘))

print(‘{:>30}‘.format(‘靠右對齊‘))

print(‘{:^30}‘.format(‘置中對齊‘))

print(‘{:*^30}‘.format(‘置中對齊‘))

輸出結果如下:

靠左對齊                           

                           靠右對齊

             置中對齊             

*************置中對齊*************

 

替換%+f,%-f和% f,以及指定符號的浮點數格式化

print(‘{:+f}; {:+f}‘.format(0.618, -0.618))

print(‘{:f}; {:f}‘.format(0.618, -0.618))

print(‘{: f}; {: f}‘.format(0.618, -0.618))

print(‘{:-f}; {:-f}‘.format(0.618, -0.618))        

輸出結果如下:

+0.618000; -0.618000

0.618000; -0.618000

 0.618000; -0.618000

0.618000; -0.618000

 

替換%x和%o,同一個值同時格式化為不同的進位輸出

print(‘int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}‘.format(55))

print(‘int: {0:d}; hex: {1:x}; oct: {0:o}; bin: {0:b}‘.format(55, 64))

print(‘int: {0:#d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}‘.format(55))

輸出結果如下:

int: 55; hex: 37; oct: 67; bin: 110111

int: 55; hex: 40; oct: 67; bin: 110111

int: 55; hex: 0x37; oct: 0o67; bin: 0b110111

 

用逗號作為千位的分隔字元

print(‘{:,}‘.format(9876543210))

print(‘{0:,}‘.format(88888888888889876543210))

輸出結果如下:

9,876,543,210

88,888,888,888,889,876,543,210

 

格式化時輸出百分比值

print(‘百分比輸出:{:.2%}‘.format(50/100))

print(‘百分比輸出:{:.2%}‘.format(1.08))

輸出結果如下:

百分比輸出:50.00%

百分比輸出:108.00%

 

格式化時輸出時間格式

import datetime

d = datetime.datetime(2015, 1, 13, 12, 30, 59)

print(‘時間格式化: {:%Y-%m-%d %H:%M:%S}‘.format(d))

輸出結果如下:

時間格式化: 2015-01-13 12:30:59

 

嵌套格式化參數

for align, text in zip(‘<^>‘, [‘左‘, ‘中‘, ‘右‘]):

    print(‘{0:{fill}{align}16}‘.format(text, fill=align, align=align))

 

width = 5

for num in range(5, 12):

    for base in ‘dXob‘:

        print(‘{0:{width}{base}}‘.format(num, base=base, width=width), end = ‘ ‘)

    print()

輸出結果如下:

左<<<<<<<<<<<<<<<

^^^^^^^中^^^^^^^^

>>>>>>>>>>>>>>>右

 

    5     5     5   101 

    6     6     6   110 

    7     7     7   111 

    8     8    10  1000 

    9     9    11  1001 

   10     A    12  1010 

   11     B    13  1011 

多個格式化模板並列

IPAddr = [192, 168, 0, 8]

print(‘{:02X}{:02X}{:02X}{:02X}‘.format(*IPAddr))

輸出結果如下:

C0A80008

 



蔡軍生 QQ:9073204 深圳

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

3.1.3 格式化字串的文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.