當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python String ljust()用法及代碼示例

Python String ljust() 方法根據指定的寬度左對齊字符串,如果未傳遞“fillchr”參數,則用空格填充行的剩餘空間。

用法:

ljust(len,fillchr)

參數:



  • len:要擴展它的字符串的寬度。
  • fillchr(可選):填充剩餘空格的字符。

返回值:

在替換原始字符串右側的給定字符後返回給定長度的新字符串。

例子1

Python3


# example string
string = 'gfg'
width = 5
  
# print left justified string
print(string.ljust(width))

輸出:

gfg  

說明:

在這裏,定義的最小寬度為 5。因此,生成的字符串的最小長度為 5。並且,字符串 ‘gfg’ 向左對齊,從而在單詞的右側留下兩個空格。

例子2

Python3


# Python3 code to demonstrate
# the working of ljust()
  
lstr = "I love geeksforgeeks"
  
# Printing the original string
print ("The original string is:\n", lstr, "\n")
  
# Printing the left aligned
# string with "-" padding
print ("The left aligned string is:")
print (lstr.ljust(40, '-'))

輸出:

The original string is:
 I love geeksforgeeks 

The left aligned string is:
I love geeksforgeeks--------------------

相關用法


注:本文由純淨天空篩選整理自AmiyaRanjanRout大神的英文原創作品 Python String ljust() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。