字符串ljust() 方法返回給定最小寬度的左對齊字符串。
用法:
string.ljust(width[, fillchar])
這裏,fillchar
是可選參數。
參數:
ljust()
方法有兩個參數:
- width- 給定字符串的寬度。如果寬度小於或等於字符串的長度,則返回原始字符串。
- 填充字符(可選)- 字符填充寬度的剩餘空間
返回:
ljust()
方法返回給定最小值內的左對齊字符串 width
。
如果定義了fillchar
,它還會用定義的字符填充剩餘空間。
示例 1:左對齊最小寬度的字符串
# example string
string = 'cat'
width = 5
# print left justified string
print(string.ljust(width))
輸出
cat
在這裏,定義的最小 width
是 5。因此,結果字符串的最小長度為 5。
並且,字符串cat
向左對齊,這使得在單詞的右側留下兩個空格。
示例 2:左對齊字符串並填充剩餘空格
# example string
string = 'cat'
width = 5
fillchar = '*'
# print left justified string
print(string.ljust(width, fillchar))
輸出
cat**
這裏,字符串cat
左對齊,右邊剩餘的兩個空格用字符*
填充。
注意:如果要右對齊字符串,請使用String rjust.你也可以使用format()字符串格式化的方法。
相關用法
- Python String lstrip()用法及代碼示例
- Python String lower()用法及代碼示例
- Python String Center()用法及代碼示例
- Python String decode()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
- Python String isprintable()用法及代碼示例
- Python String translate()用法及代碼示例
- Python String title()用法及代碼示例
- Python String replace()用法及代碼示例
- Python String split()用法及代碼示例
- Python String format_map()用法及代碼示例
- Python String zfill()用法及代碼示例
- Python String max()用法及代碼示例
注:本文由純淨天空篩選整理自 Python String ljust()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。