Python 中的 ljust() 函数通过用指定的字符填充给定最小长度的字符串,帮助将字符串左对齐。如果缺少 fillchar 参数,则空格被视作默认填充字符。
string.ljust(width[, fillchar]) #where width is an integer value
ljust() 函数接受两个参数。fillchar 参数必须是单个字符。如果给定的 fillchar 参数包含多个字符,则会抛出 TypeError。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| width | 返回字符串的宽度 | 必需 |
| 填充字符 | 用于填充缺失字符的字符 | 可选 |
返回值始终是一个字符串。在这里,fillchar 字符填充在字符串的右侧。如果指定的宽度小于或等于字符串的长度,则返回原始字符串作为输出。
| 输入 | 返回值 |
|---|---|
| 如果参数 | 左对齐字符串 |
# example string
string = 'Python'
length = 7
# print left justified string
print(string.ljust(length))
输出
Python
# example string
string = 'Python'
length = 10
fill = '*'
# print left justified string
print(string.ljust(length, fill))
输出
Python****