萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python rjust() 方法詳解:字串靠右填充對齊

方法簽名

str.rjust(width, fillchar=' ') -> str

行為定義

回傳長度至少為 width 的新字串,原字串靠右,左側以 fillchar 填充。若 len(s) >= width,直接回傳原字串副本。

基本範例

>> 'hello'.rjust(10)
'     hello'
>>> 'hello'.rjust(10, '-')
'-----hello'
>>> 'hello'.rjust(3)
'hello'
>>> ''.rjust(5, '*')
'*****'

實際應用:數字靠右對齊 (財務報表、編號)

輸出:

Revenue        1,234,567
Expense          234,567
Profit        1,000,000

對稱方法對照

方法對齊範例 (width=10, fill='-')
ljust靠左'hello-----'
rjust靠右'-----hello'
center置中'--hello---'

f-string / format 替代方案 (推薦)

>> f'{"hello":>10}'
'     hello'
>>> f'{"hello":->10}'
'-----hello'
>>> f'{1234:>10,}'
'   1,234'
>>> f'{1234:0>10,}'
'00001,234'

格式化字串支援數字格式化 (千分位、小數位、正負號)、對齊、填充字一次完成,語意更清晰。

注意事項

  • fillchar 必須長度 1。
  • 寬字元 (中文、Emoji) 顯示寬度 ≠ 字元數,終端機對齊可能錯位;需用 wcwidth 計算視覺寬度後再填充。
  • 原字串不變更。
copyright © 萬盛學電腦網 all rights reserved