Tutorial Study Image

Python ljust()

Python 中的 ljust() 函数通过用指定的字符填充给定最小长度的字符串,帮助将字符串左对齐。如果缺少 fillchar 参数,则空格被视作默认填充字符。


string.ljust(width[, fillchar]) #where width is an integer value
 

ljust() 参数

ljust() 函数接受两个参数。fillchar 参数必须是单个字符。如果给定的 fillchar 参数包含多个字符,则会抛出 TypeError。

参数 描述 必需/可选
width 返回字符串的宽度 必需
填充字符 用于填充缺失字符的字符 可选

ljust() 返回值

返回值始终是一个字符串。在这里,fillchar 字符填充在字符串的右侧。如果指定的宽度小于或等于字符串的长度,则返回原始字符串作为输出。

输入 返回值
如果参数 左对齐字符串

Python 中 ljust() 方法的示例

示例 1:如何在 Python 中将字符串左对齐到最小宽度?


# example string
string = 'Python'
length = 7

# print left justified string
print(string.ljust(length))
 

输出


Python

示例 2:如何在 Python 中左对齐字符串并填充剩余空间?


# example string
string = 'Python'
length = 10
fill = '*'

# print left justified string
print(string.ljust(length, fill))
 

输出


Python****