Python如何對齊字串
阿新 • • 發佈:2020-07-31
問題
你想通過某種對齊方式來格式化字串
解決方案
對於基本的字串對齊操作,可以使用字串的 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*****' >>>
函式 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*****' >>>
當格式化多個值的時候,這些格式程式碼也可以被用在 format()
方法中。比如:
>>> '{:>10s} {:>10s}'.format('Hello','World') ' Hello World' >>>
format()
函式的一個好處是它不僅適用於字串。它可以用來格式化任何值,使得它非常的通用。 比如,你可以用它來格式化數字:
>>> x = 1.2345 >>> format(x,'>10') ' 1.2345' >>> format(x,'^10.2f') ' 1.23 ' >>>
討論
在老的程式碼中,你經常會看到被用來格式化文字的 % 操作符。比如:
>>> '%-20s' % text 'Hello World ' >>> '%20s' % text ' Hello World' >>>
但是,在新版本程式碼中,你應該優先選擇 format()
函式或者方法。 format()
要比 % 操作符的功能更為強大。 並且 format()
也比使用 ljust()
,rjust()
或 center()
方法更通用, 因為它可以用來格式化任意物件,而不僅僅是字串。
如果想要完全瞭解 format()
函式的有用特性, 請參考 線上Python文件
以上就是Python如何對齊字串的詳細內容,更多關於Python對齊字串的資料請關注我們其它相關文章!