Python中字符串格式化str.format的詳細(xì)介紹
前言
Python 在 2.6 版本中新加了一個(gè)字符串格式化方法: str.format() 。它的基本語法是通過 {} 和 : 來代替以前的 %.。
格式化時(shí)的占位符語法:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
“映射”規(guī)則
通過位置
str.format() 可以接受不限個(gè)參數(shù),位置可以不按順序:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
通過關(guān)鍵字參數(shù)
使用關(guān)鍵參數(shù)時(shí)字符串中需要提供參數(shù)名:
>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'
通過對象屬性
str.format() 可以直接讀取用戶屬性:
>>> class User(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __str__(self):
... return "{self.name}({self.age})".format(self=self)
...
... def __repr__(self):
... return self.__str__()
...
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'
通過下標(biāo)
在需要格式化的字符串內(nèi)部可以通過下標(biāo)來訪問元素:
>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)
指定轉(zhuǎn)化
可以指定字符串的轉(zhuǎn)化類型:
conversion ::= "r" | "s" | "a"
其中 "!r" 對應(yīng) repr(); "!s" 對應(yīng) str(); "!a" 對應(yīng) ascii()。 示例:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
格式限定符
填充與對齊
填充常跟對齊一起使用。^, <, > 分別是居中、左對齊、右對齊,后面帶寬度, : 號(hào)后面帶填充的字符,只能是一個(gè)字符,不指定則默認(rèn)是用空格填充。
>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'
浮點(diǎn)精度
用 f 表示浮點(diǎn)類型,并可以在其前邊加上精度控制:
>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'
還可以為浮點(diǎn)數(shù)指定符號(hào),+ 表示在正數(shù)前顯示 +,負(fù)數(shù)前顯示 -; (空格)表示在正數(shù)前加空格,在幅負(fù)數(shù)前加 -;- 與什么都不加({:f})時(shí)一致:
>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'
指定進(jìn)制
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'
千位分隔符
可以使用 "," 來作為千位分隔符:
>>> '{:,}'.format(1234567890)
'1,234,567,890'
百分?jǐn)?shù)顯示
>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'
事實(shí)上,format 還支持更多的類型符號(hào):
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
其他技巧
占位符嵌套
某些時(shí)候占位符嵌套還是很有用的:
>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
... for base in "dXob":
... print("{0:{width}{base}}".format(num, base=base, width=5), 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
作為函數(shù)使用
可以先不指定格式化參數(shù),而是在不要的地方作為函數(shù)來調(diào)用:
>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="suodhuoty@gmail.com"))
Your email address was sudohuoty@gmail.com
轉(zhuǎn)義大括號(hào)
當(dāng)在字符串中需要使用大括號(hào)時(shí)可以用大括號(hào)轉(zhuǎn)義:
>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- Python中用format函數(shù)格式化字符串的用法
- 淺談Python 字符串格式化輸出(format/printf)
- Python常見格式化字符串方法小結(jié)【百分號(hào)與format方法】
- Python中應(yīng)該使用%還是format來格式化字符串
- Python格式化輸出字符串方法小結(jié)【%與format】
- 淺析python3字符串格式化format()函數(shù)的簡單用法
- python字符串格式化(%格式符和format方式)
- python格式化字符串的實(shí)戰(zhàn)教程(使用占位符、format方法)
- Python字符串格式化format()方法運(yùn)用實(shí)例
相關(guān)文章
keras使用Sequence類調(diào)用大規(guī)模數(shù)據(jù)集進(jìn)行訓(xùn)練的實(shí)現(xiàn)
這篇文章主要介紹了keras使用Sequence類調(diào)用大規(guī)模數(shù)據(jù)集進(jìn)行訓(xùn)練的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
OpenCV-Python使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取
在圖像的處理過程中,經(jīng)常需要從圖像中將前景對象作為目標(biāo)圖像分割或者提取出來。本文就介紹了使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取,感興趣的可以了解一下2021-06-06
Pytorch 神經(jīng)網(wǎng)絡(luò)—自定義數(shù)據(jù)集上實(shí)現(xiàn)教程
今天小編就為大家分享一篇Pytorch 神經(jīng)網(wǎng)絡(luò)—自定義數(shù)據(jù)集上實(shí)現(xiàn)教程,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python關(guān)鍵字傳遞參數(shù)實(shí)例分析
在本篇文章里小編給大家整理的是一篇關(guān)于python關(guān)鍵字傳遞參數(shù)實(shí)例分析內(nèi)容,有需要的朋友們可以學(xué)習(xí)參考下。2021-06-06
使用Python的Django和layim實(shí)現(xiàn)即時(shí)通訊的方法
這篇文章主要介紹了使用Python的Django和layim實(shí)現(xiàn)即時(shí)通訊的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
OpenCV哈里斯(Harris)角點(diǎn)檢測的實(shí)現(xiàn)
這篇文章主要介紹了OpenCV哈里斯 (Harris)角點(diǎn)檢測,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
python3實(shí)現(xiàn)短網(wǎng)址和數(shù)字相互轉(zhuǎn)換的方法
這篇文章主要介紹了python3實(shí)現(xiàn)短網(wǎng)址和數(shù)字相互轉(zhuǎn)換的方法,涉及Python操作字符串的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04

