Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format()该贾,它增強(qiáng)了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 捌臊。
format 函數(shù)可以接受不限個(gè)參數(shù)杨蛋,位置可以不按順序。
# 基本用法
>>> "{} {}".format("hello", "world") # 不設(shè)置指定位置理澎,按默認(rèn)順序
'hello world'
>>> "{0} {1}".format("hello", "world") # 設(shè)置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 設(shè)置指定位置
'world hello world'
>>> value = 4 * 20
>>> 'The value is {}.'.format(value)
'The value is 80.'
str.format() 格式化數(shù)字一大波花里胡哨的用法:
>>> print ("{:+.4f}".format(3.1415926)) # 帶符號(hào)保留小數(shù)點(diǎn)后四位
+3.1416
>>> print ("{:+.4f}".format(-3)) # 帶符號(hào)保留小數(shù)點(diǎn)后四位
-3.0000
>>> print ("{:.0f}".format(3.1415926)) # 不帶小數(shù)
3
>>> print ("{:0>2d}".format(5)) # 數(shù)字補(bǔ)零 (填充左邊, 寬度為2)
05
>>> print ("{:0<3d}".format(5)) # 數(shù)字補(bǔ)零 (填充右邊, 寬度為3)
500
>>> print ("{:x<3d}".format(5)) # 數(shù)字補(bǔ)x (填充右邊, 寬度為3)
5xx
>>> print ("{:,}".format(10000000)) # 以逗號(hào)分隔的數(shù)字格式
10,000,000
>>> print ("{:.2%}".format(0.25)) # 百分比格式逞力,小數(shù)點(diǎn)保留兩位
25.00%
>>> print ("{:2e}".format(1000000000)) # 指數(shù)記法
1.000000e+09
>>> print ("{:>10d}".format(13)) # 右對(duì)齊 (默認(rèn), 寬度為10), 等同于"{:10d}".format(13)
13
>>> print ("{:^10d}".format(13)) # 中間對(duì)齊 (寬度為10)
13
>>> print ("{:<10d}".format(13)) # 左對(duì)齊 (寬度為10)
13
# 各種進(jìn)制轉(zhuǎn)換
>>> '{:b}'.format(11)
1011
>>> '{:d}'.format(11)
11
>>> '{:o}'.format(11)
13
>>> '{:x}'.format(11)
b
>>> '{:#x}'.format(11)
0xb
>>> '{:#X}'.format(11)
0XB
^, <, > 分別是居中、左對(duì)齊糠爬、右對(duì)齊寇荧,后面帶寬度, : 號(hào)后面帶填充的字符执隧,只能是一個(gè)字符揩抡,不指定則默認(rèn)用空格填充户侥。
\+ 表示在正數(shù)前顯示 +,負(fù)數(shù)前顯示 -峦嗤; (空格)表示在正數(shù)前加空格
b蕊唐、d、o烁设、x 分別是二進(jìn)制替梨、十進(jìn)制、八進(jìn)制装黑、十六進(jìn)制副瀑。
此外我們可以使用大括號(hào) {} 來轉(zhuǎn)義大括號(hào),如下實(shí)例:
>>> print ("{} 對(duì)應(yīng)的位置是 {{0}}".format("runoob"))
runoob 對(duì)應(yīng)的位置是 {0}
稍微復(fù)雜的用法:
metro_areas = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833))]
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas:
if longitude <= 0:
print(fmt.format(name, latitude, longitude))
這里用到了嵌套元組拆包和str.format()結(jié)合的方法
1.每個(gè)元組內(nèi)有 4 個(gè)元素曹体,其中最后一個(gè)元素是一對(duì)坐標(biāo)
2.我們把輸入元組的最后一個(gè)元素拆包到由變量構(gòu)成的元組里俗扇,這樣就獲取了坐標(biāo)
3.if longitude <= 0: 這個(gè)條件判斷把輸出限制在西半球的城市
輸出結(jié)果
| lat. | long.
Mexico City | 19.4333 | -99.1333
New York-Newark | 40.8086 | -74.0204
Sao Paulo | -23.5478 | -46.6358
這里也順便介紹一下f-strings的用法,該方法和str.format()
相似箕别。 可以簡(jiǎn)化之前%s之類的代碼铜幽。在Python3.6版本引進(jìn)
格式化的字符串文字以 f 開頭,它們包含用大括號(hào)括起來的替換字段串稀。詳見PEP498
#基本用法
>> name = 'Fred'
>> print(f"He said his name is {name}.")
'He said his name is Fred.'
# 基本用法2
>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."
# 三種不同的寫法
>>> value = 4 * 20
>>> 'The value is {}.'.format(value)
>>> 'The value is %s.' % value
>>> f'The value is {value}.'
# 結(jié)果都是:
'The value is 80.'
# 時(shí)間格式化實(shí)例
>>> import datetime
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
以上所有用法均在3.85版本測(cè)試通過, 部分實(shí)例引用官方文檔除抛,菜鳥教程及《流暢的python》