文章作者:Tyan
博客:noahsnail.com | CSDN | 簡書
0. 測試環境
Python 3.6.9
1. 引言
Python中格式化字符串的方式有,一種是用%
操作符來進行字符串格式化,一種是使用str.format()
來進行字符串格式化,本文主要介紹str.format()
方式,這種方式更主流,也是官方推薦的方式,%
的方式後面會逐漸淘汰。
2. 格式化字符串
2.1 基本語法
格式化字符串包含用大括號{}
括起來的“替換字段”,。大括號中不包含的內容被視爲正常文本,會原樣輸出。注意:如果要在文本中輸出大括號,需要使用{{
和}}
來轉義,不是使用場景的轉義字符\
。示例如下:
>>> 'This is a format {}.'.format('test')
'This is a format test.'
>>> 'This is {{}} test.'.format()
'This is {} test.'
下面是“替換字段”的語法,後面的示例中會具體講到:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | digit+]
attribute_name ::= identifier
element_index ::= digit+ | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
2.2 位置參數標識符
格式化字符串中,默認情況下{}
中可以不加位置標識符,即'{} {}'.format(a, b)
與'{0} {1}'.format(a, b)
是等價的,但如果位置標識符在字符串中不是按參數順序出現的,則需要顯示的指明位置標識符。示例代碼如下:
>>> '{0} {1}'.format('one', 'two')
'one two'
>>> '{} {}'.format('one', 'two')
'one two'
>>> '{1} {0}'.format('one', 'two')
'two one'
>>> '{0} {1} {0}'.format('one', 'two')
'one two one'
2.3 設置參數
格式化字符串中可以使用變量、字典、列表索引、類的屬性等來設置參數。示例代碼如下:
print('Name: {name}, URL: {url}'.format(name='Tyan', url='http://noahsnail.com'))
name = 'Tyan'
url = 'http://noahsnail.com'
print('Name: {}, URL: {}'.format(name, url))
site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}
print('Name: {site[name]}, URL: {site[url]}'.format(site=site))
print('Name: {name}, URL: {url}'.format(**site))
site = ['Tyan', 'http://noahsnail.com']
print('Name: {0[0]}, URL: {0[1]}'.format(site))
class Test(object):
def __init__(self):
self.name = 'Tyan'
self.url = 'http://noahsnail.com'
print('Name: {0.name}, URL: {0.url}'.format(Test()))
site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}
print('Name: {name}, URL: {url}'.format(**site))
# Output
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
2.3 轉換標誌(conversion)
轉換標誌以!
開始,主要有三種!s
、!r
、!a
,分別會調用參數對象的__str__
,__repr__
,__ascii__
方法。
class Test(object):
def __str__(self):
return 'Test str function.'
def __repr__(self):
return 'Test repr function.'
def __ascii__(self):
return 'Test ascii function.'
print('str: {t!s}, repr: {t!r}, ascii: {t!a}'.format(t=Test()))
# Ouput
str: Test str function., repr: Test repr function., ascii: Test repr function.
2.4 格式化說明(format_spec)
格式化說明包含了值表示的說明,包括字段寬度、對其方式、填充、小數準確率等,其以:
開頭。標準格式化說明符的一般形式爲:
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
<
表示輸出結果左對齊,>
是右對齊,^
是居中對其,=
表示填充值在符號之後數字之前,例如+00001234
。+
表示正負數字都要帶符號,-
表示只有負數需要帶負號,表示正數前面帶空格,負數前面帶負號。
- 數字表示。
b
表示二進制格式,c
表示將整數轉換爲字符,d
表示十進制整數,o
表示八進制格式,x,X
表示十六進制格式,x
大於9的字母爲小寫,X
大於9的字母爲大寫。默認爲d
。 - 其它說明符的具體解釋可參考文檔[1]。
示例及結果如下:
print('{:<8}'.format('1234'))
print('{:>8}'.format('1234'))
print('{:^8}'.format('1234'))
print('{:*>8}'.format('1234'))
print('{:*<8}'.format('1234'))
print('{:*^8}'.format('1234'))
print('{:+f}; {:+f}'.format(3.14, -3.14))
print('{: f}; {: f}'.format(3.14, -3.14))
print('{:-f}; {:-f}'.format(3.14, -3.14))
print('int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(100))
print('int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(100))
print('{:,}'.format(100000000))
print('{:.2e}'.format(100000000))
print('percentage: {:.2%}'.format(1 / 3))
import datetime
print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
# Output
1234
1234
1234
****1234
1234****
**1234**
+3.140000; -3.140000
3.140000; -3.140000
3.140000; -3.140000
int: 100; hex: 64; oct: 144; bin: 1100100
int: 100; hex: 0x64; oct: 0o144; bin: 0b1100100
100,000,000
1.00e+08
percentage: 33.33%
2020-06-18 19:36:38