Python如何對齊字符串
問題
你想通過某種對齊方式來格式化字符串
解決方案
對于基本的字符串對齊操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。比如:
>>> text = ’Hello World’>>> text.ljust(20)’Hello World ’>>> text.rjust(20)’ Hello World’>>> text.center(20)’ Hello World ’>>>
所有這些方法都能接受一個可選的填充字符。比如:
>>> text.rjust(20,’=’)’=========Hello World’>>> text.center(20,’*’)’****Hello World*****’>>>
函數(shù) format() 同樣可以用來很容易的對齊字符串。 你要做的就是使用 <,> 或者 ^ 字符后面緊跟一個指定的寬度。比如:
>>> format(text, ’>20’)’ Hello World’>>> format(text, ’<20’)’Hello World ’>>> format(text, ’^20’)’ Hello World ’>>>
如果你想指定一個非空格的填充字符,將它寫到對齊字符的前面即可:
>>> format(text, ’=>20s’)’=========Hello World’>>> format(text, ’*^20s’)’****Hello World*****’>>>
當(dāng)格式化多個值的時候,這些格式代碼也可以被用在 format() 方法中。比如:
>>> ’{:>10s} {:>10s}’.format(’Hello’, ’World’)’ Hello World’>>>
format() 函數(shù)的一個好處是它不僅適用于字符串。它可以用來格式化任何值,使得它非常的通用。 比如,你可以用它來格式化數(shù)字:
>>> x = 1.2345>>> format(x, ’>10’)’ 1.2345’>>> format(x, ’^10.2f’)’ 1.23 ’>>>
討論
在老的代碼中,你經(jīng)常會看到被用來格式化文本的 % 操作符。比如:
>>> ’%-20s’ % text’Hello World ’>>> ’%20s’ % text’ Hello World’>>>
但是,在新版本代碼中,你應(yīng)該優(yōu)先選擇 format() 函數(shù)或者方法。 format() 要比 % 操作符的功能更為強大。 并且 format() 也比使用 ljust() , rjust() 或 center() 方法更通用, 因為它可以用來格式化任意對象,而不僅僅是字符串。
如果想要完全了解 format() 函數(shù)的有用特性, 請參考 在線Python文檔
以上就是Python如何對齊字符串的詳細(xì)內(nèi)容,更多關(guān)于Python對齊字符串的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
