Python 字串 ljust() 方法



Python 字串 ljust() 方法用於將字串左對齊,並指定寬度。如果指定的寬度大於字串的長度,則字串的剩餘部分將填充 fillchar

預設的 fillchar 是空格。如果寬度小於或等於給定字串長度,則返回原始字串。

注意:只能使用一個特定字元來填充字串的剩餘部分,作為 fillchar。

語法

以下是 Python 字串 ljust() 方法的語法

str.ljust(width[, fillchar])

引數

  • width − 這是填充後字串的總長度。

  • fillchar − 這是填充字元;預設為空格(可選)。

返回值

此方法返回一個左對齊的字串,其中填充字元作為引數指定,用於替換空格。如果寬度小於字串長度,則返回原始字串。

示例

在以下示例中,建立的字串 "this is string example....wow!!!" 左對齊。然後,右側的剩餘空格使用指定的字元 "0" 作為 fillchar 引數,使用 Python 字串 ljust() 方法填充。然後檢索結果

# Initializing the string
str = "this is string example....wow!!!";
print (str.ljust(50, '0'))

執行以上程式時,會產生以下結果

this is string example....wow!!!000000000000000000

示例

以下是一個示例,其中生成一個長度為 89 的新字串,並將建立的字串 ‘Programming’ 左對齊。由於未提供 fillchar,因此使用預設的空格值。因此,檢索到 ‘Programming’ 及其右側的 78 個空格。

text = 'Programming'
# left-aligning the string
x = text.ljust(89)
print('The string after aligning is:', x)

執行以上程式碼時,會獲得以下輸出

The string after aligning is: Programming                                                                              

示例

在下面給出的示例中,我們使用 3 個鍵值對建立一個字典。然後我們嘗試列印用 ":" 分隔的值對,我們使用 ljust() 方法來做到這一點。

# providing the dictionary
dictionary = {'Name':'Sachin', 'Sports':'Cricket', 'Age':49}
# iterating on each item of the dictionary
for keys, value in dictionary.items():
   print(str(keys).ljust(6, ' '),":", str(value))

以上程式碼的輸出如下

Name   : Sachin
Sports : Cricket
Age    : 49     

示例

以下是一個示例,用於說明如果將多個字元作為 fillchar 引數傳遞,則會丟擲錯誤,因為 fillchar 引數應只包含一個字元

text = 'Coding'
# providingh more than one fillchar character
x = text.ljust(67, '*#')
print('The new string is:', x) 

以下是以上程式碼的輸出

Traceback (most recent call last):
   File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in 
      x = text.ljust(67, '*#')
TypeError: The fill character must be exactly one character long
python_strings.htm
廣告