Python 字符串格式化

字符串格式化


對(duì)于如何輸出格式化的字符串座掘,是一個(gè)常見的問題。有時(shí)需要對(duì)字符串進(jìn)行對(duì)齊房蝉,或者按照指定的列寬格式化字符串,亦或是對(duì)字符串進(jìn)行拼接径筏,有時(shí)候還需要構(gòu)造內(nèi)嵌變量的字符串等。Python 提供了一些方法對(duì)上述情況進(jìn)行實(shí)現(xiàn)糠悼。

ljust()、rjust()浅乔、center()


對(duì)于基本字符串對(duì)齊操作倔喂,可以使用字符串內(nèi)置方法 ljust()rjust()靖苇、center()席噩。如下示例:

>>> text = "Hello World"
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '
>>>

上述三個(gè)方法有兩個(gè)參數(shù) widthfillcharwidth 用于返回長度為 width 的字符串顾复,使用指定的 fillchar 填充空位(默認(rèn)使用 ASCII 空格符班挖,可指定其他字符)。

其中 ljust() 原字符串在其中靠左對(duì)齊芯砸,rjust() 靠右對(duì)齊萧芙,center() 在正中给梅。

嘗試使用指定非空格的 fillchar 作為填充字符,例如:

>>> text.ljust(20, '-')
'Hello World---------'
>>> text.rjust(20, '=')
'=========Hello World'
>>> text.center(20, '*')
'****Hello World*****'

這三個(gè)方法還有個(gè)特性双揪,如果參數(shù) width 小于等于 len(s) 字符串的長度动羽,則返回原字符串的副本。

>>> len(text)
11
>>> text.ljust(11)
'Hello World'
>>> text.rjust(10)
'Hello World'
>>> text.center(9)
'Hello World'

format()


字符串對(duì)齊

除了使用上述三種方法對(duì)字符串進(jìn)行對(duì)齊渔期,format() 也能夠?qū)崿F(xiàn)對(duì)齊字符串运吓。

各種對(duì)齊選項(xiàng)含義如下:

選項(xiàng) 含義
'<' 強(qiáng)制字段在可用空間內(nèi)向左對(duì)齊(大多數(shù)對(duì)象的默認(rèn)值)
'>' 強(qiáng)制字段在可用空間內(nèi)向右對(duì)齊(數(shù)字的默認(rèn)值)
'^' 強(qiáng)制字段在可用空間內(nèi)居中

使用 format() 對(duì)字符串進(jìn)行對(duì)齊,在上述對(duì)齊選項(xiàng)后面添加指定寬度疯趟,示例如下:

>>> format(text, '>20')
'         Hello World'
>>> format(text, '<20')
'Hello World         '
>>> format(text, '^20')
'    Hello World     '

如果需要指定非空格填充字符拘哨,可在對(duì)齊選項(xiàng)前面添加 fill 字符,可以是任意字符信峻。

>>> format(text, '->20')
'---------Hello World'
>>> format(text, '=<20')
'Hello World========='
>>> format(text, '*^20')
'****Hello World*****'

format() 可用于格式化多個(gè)值倦青,比如:

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'

s 為字符串表示類型,表示字符串格式盹舞,字符串的默認(rèn)類型产镐,可省略。

format() 不單只適用于字符串踢步。它可以格式化任何值癣亚。例如,格式化數(shù)字:

>>> format(x, '>10')
'    1.2345'
>>> format(x, '^10.2f')
'   1.23   '

f 為浮點(diǎn)型表示類型获印,表示定點(diǎn)表示述雾。其中 .2f 表示以 f 格式化的浮點(diǎn)數(shù)值在小數(shù)點(diǎn)后顯示 2 個(gè)數(shù)位。

相比 ljust()蓬豁,rjust()绰咽,center()format() 更通用地粪,同時(shí)還可以格式化任意對(duì)象,不僅僅是字符串琐谤。

替換內(nèi)嵌變量字符串

字符串的 format() 方法蟆技,能夠用指定的值替換內(nèi)嵌變量字符串中的變量。

>>> s = '{name} was born in {country}'
>>> s.format(name='Guido',country='Netherlands')
'Guido was born in Netherlands'

如果被替換的變量能夠在變量域中找到斗忌,可以結(jié)合使用 format_map()vars()质礼。示例如下:

>>> name = 'Guido'
>>> country = 'Netherlands'
>>> s.format_map(vars())
'Guido was born in Netherlands'
>>>

format()format_map() 有一個(gè)缺陷,不能很好處理變量缺失的情況织阳,如下示例:

>>> s.format(name='Gudio')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'country'

這里可以使用 __missing__() 方法眶蕉,定義一個(gè)含此方法的字典來避免上面發(fā)生的錯(cuò)誤。例如:

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> s.format_map(Default(name='Gudio'))
'Guido was born in country'

若需完全了解 format() 函數(shù)的相關(guān)特性唧躲,請(qǐng)參考 Python文檔造挽。

join()


若需合并的字符串是在一個(gè)序列或者 iterable 中碱璃,建議使用 join() 方法。示例如下:

>>> words = ['Hello', 'World']
>>> ' '.join(words)
'Hello World'
>>> ','.join(words)
'Hello,World'

join(iterable) 方法返回的是一個(gè)由 iterable 中的字符串拼接的字符串饭入。如果 iterable 中存在任何非字符值包括 bytes 對(duì)象則會(huì)引發(fā) TypeError嵌器。調(diào)用該方法的字符串將作為元素之間的分隔。例如上述例子的空格 ' '和 逗號(hào) ','谐丢。

還有一種拼接字符串的方法是用加號(hào) +爽航,但是這種效率通常是非常低的。這種加號(hào)連接會(huì)引起內(nèi)存復(fù)制以及垃圾回收機(jī)制乾忱。不建議使用下列方法連接字符串:

s = ''
for word in words:
    s += word

textwrap


長字符串輸出的時(shí)候讥珍,有時(shí)需要進(jìn)行一定的格式化輸出,如下示例:

>>> s = "The Zen of Python, by Tim Peters \
... Beautiful is better than ugly.\
... Explicit is better than implicit. \
... Simple is better than complex. \
... Complex is better than complicated. \
... Flat is better than nested. \
... Sparse is better than dense. \
... Readability counts. \
... Special cases aren't special enough to break the rules. \
... Although practicality beats purity. \
... Errors should never pass silently. \
... Unless explicitly silenced. \
... In the face of ambiguity, refuse the temptation to guess. \
... There should be one-- and preferably only one --obvious way to do it. \
... Although that way may not be obvious at first unless you're Dutch. \
... Now is better than never. \
... Although never is often better than *right* now. \
... If the implementation is hard to explain, it's a bad idea. \
... If the implementation is easy to explain, it may be a good idea. \
... Namespaces are one honking great idea -- let's do more of those!"

>>> import textwrap
>>> print(textwrap.fill(s, 70))
The Zen of Python, by Tim Peters Beautiful is better than
ugly.Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!

>>> print(textwrap.fill(s, 40))
The Zen of Python, by Tim Peters
Beautiful is better than ugly.Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!

>>> print(textwrap.fill(s, 40, initial_indent='    '))
    The Zen of Python, by Tim Peters
Beautiful is better than ugly.Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!

>>> print(textwrap.fill(s, 40, subsequent_indent='    '))
The Zen of Python, by Tim Peters
    Beautiful is better than
    ugly.Explicit is better than
    implicit. Simple is better than
    complex. Complex is better than
    complicated. Flat is better than
    nested. Sparse is better than dense.
    Readability counts. Special cases
    aren't special enough to break the
    rules. Although practicality beats
    purity. Errors should never pass
    silently. Unless explicitly
    silenced. In the face of ambiguity,
    refuse the temptation to guess.
    There should be one-- and preferably
    only one --obvious way to do it.
    Although that way may not be obvious
    at first unless you're Dutch. Now is
    better than never. Although never is
    often better than *right* now. If
    the implementation is hard to
    explain, it's a bad idea. If the
    implementation is easy to explain,
    it may be a good idea. Namespaces
    are one honking great idea -- let's
    do more of those!
>>>

textwrap 模塊中的 fill 方法用于對(duì) text 中的單獨(dú)段落自動(dòng)換行窄瘟,返回包含被換行段落的單獨(dú)字符串串述。fill 函數(shù)屬于快捷函數(shù),若更復(fù)雜的情況寞肖,建議使用 TextWrapper 提高效率纲酗。可參閱 textwrap.TextWrapper 文檔 獲取更多的內(nèi)容新蟆。

參考資料


來源

  1. David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O'Reilly Media.2013.
  2. "6.1. string — Common string operations".docs.python.org.Retrieved 7 January 2020
  3. '2. Built-in Functions".docs.python.org.Retrieved 6 January 2020
  4. "4. Built-in Types".docs.python.org.Retrieved 3 January 2020
  5. "6.4. textwrap — Text wrapping and filling".docs.python.org.Retrieved 9 January 2020

以上就是本篇的主要內(nèi)容


<center>歡迎關(guān)注『書所集錄』公眾號(hào)</center>

<center><img src="https://i.loli.net/2020/01/02/5AXcl4MoexgnftR.jpg"></center>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末觅赊,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子琼稻,更是在濱河造成了極大的恐慌吮螺,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件帕翻,死亡現(xiàn)場(chǎng)離奇詭異鸠补,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)嘀掸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門紫岩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人睬塌,你說我怎么就攤上這事泉蝌。” “怎么了揩晴?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵勋陪,是天一觀的道長。 經(jīng)常有香客問我硫兰,道長诅愚,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任劫映,我火速辦了婚禮违孝,結(jié)果婚禮上刹前,老公的妹妹穿的比我還像新娘。我一直安慰自己等浊,他們只是感情好腮郊,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著筹燕,像睡著了一般轧飞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上撒踪,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天过咬,我揣著相機(jī)與錄音,去河邊找鬼制妄。 笑死掸绞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的耕捞。 我是一名探鬼主播衔掸,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼俺抽!你這毒婦竟也來了敞映?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤磷斧,失蹤者是張志新(化名)和其女友劉穎振愿,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體弛饭,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡冕末,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了侣颂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片档桃。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖横蜒,靈堂內(nèi)的尸體忽然破棺而出胳蛮,到底是詐尸還是另有隱情,我是刑警寧澤丛晌,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布,位于F島的核電站斗幼,受9級(jí)特大地震影響澎蛛,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蜕窿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一谋逻、第九天 我趴在偏房一處隱蔽的房頂上張望呆馁。 院中可真熱鬧,春花似錦毁兆、人聲如沸浙滤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽纺腊。三九已至,卻和暖如春茎芭,著一層夾襖步出監(jiān)牢的瞬間揖膜,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來泰國打工梅桩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留壹粟,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓宿百,卻偏偏與公主長得像趁仙,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子垦页,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359