Python str rjust()方法

目錄

描述

語法

參數說明

返回值

使用示例

1. 僅指定width參數

2. 指定填充字符

注意事項

1. fill_character參數必須是字符或長度爲1的字符串

2. 當字符串本身的長度不小於width值時


 

描述

Python rjust()方法是字符串的排版方法,它將原字符串右對齊,並使用空格填充至指定長度,並返回新的字符串。如果指定的長度小於原字符串長度,則直接新返回的字符串與原字符串相同。

 

語法

str.rjust(width, fill_character)

 

參數說明

名稱 說明 備註
width 排版字符串寬度 整型參數
fill_character 填充字符 可省略的字符參數,省略時默認等於空格符

 

返回值

rjust方法返回一個右對齊排版的字符串。

 

使用示例

1. 僅指定width參數

fill_character參數省略時,默認填充字符是空格:

>>> demo = "copyright"
>>> result = demo.rjust(50)
>>> id(demo)
4486574000
>>> id(result)
4487419464
>>> len(result)
50
>>> result
'                                         copyright'

2. 指定填充字符

>>> demo = "huawei"
>>> result = demo.rjust(30, "*")
>>> result
'************************huawei'

 

注意事項

1. fill_character參數必須是字符或長度爲1的字符串

fill_character必須是字符類型或者是長度爲1的字符串,否則Python報錯TypeError

>>> demo = "metadata"
>>> result = demo.rjust(30, "--")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long

2. 當字符串本身的長度不小於width值時

當字符串本身的長度大於或等於width的值時,rjust()方法返回原字符串。

>>> demo = "start"
>>> result = demo.rjust(1, "-")
>>> result
'start'
>>> id(demo)
4486464488
>>> id(result)
4486464488

 

發佈了165 篇原創文章 · 獲贊 144 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章