字符串格式化
對(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ù) width
和 fillchar
,width
用于返回長度為 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)容新蟆。
參考資料
來源
- David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O'Reilly Media.2013.
- "6.1. string — Common string operations".docs.python.org.Retrieved 7 January 2020
- '2. Built-in Functions".docs.python.org.Retrieved 6 January 2020
- "4. Built-in Types".docs.python.org.Retrieved 3 January 2020
- "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>