Python ljust 函数用于将字符串靠左对齐。ljust 会用指定的字符(默认为空格)填充剩余的宽度,并返回新的字符串。本节将通过示例讨论如何使用 ljust。
ljust 函数的语法如下所示。
- 宽度: 请指定字符串的对齐长度。
- 字符: 如果省略此参数,它将默认使用空格。要更改默认值,请指定要在剩余宽度中使用的字符。
String_Value.ljust(Width, Char)
Python ljust 方法示例
ljust 函数只接受一个字符作为第二个参数。以下示例将帮助您理解该函数。
下面的 Str2 语句将字符串变量 Str1 左对齐。并用默认的空格填充剩余的宽度并打印输出。
您可能会对空格感到困惑,因此我们使用了 '=' 作为第二个参数。这个 Python Str3 语句用 '=' 符号填充剩余的宽度。
Python ljust 函数返回的是一个新字符串,而不是修改原始字符串。
要修改原始字符串,请编写以下 字符串方法 语句。
Str1 = Str1.ljust()
ljust 函数只允许将单个字符作为第二个参数。让我们看看当我们在 Str4 和 Str5 中使用两个字符(+ 和 *)时会发生什么。
它会抛出错误,提示:“TypeError: The fill character must be exactly one character long”(TypeError: 填充字符必须正好是一个字符长)。
Str1 = 'Tutorial Gateway'
Str2 = Str1.ljust(30)
print('Justifying Left with White sapces is =', Str2)
# Let us place second parameter as well
Str3 = Str1.ljust(30, '=')
print("Justifying Left with '=' using is =", Str3)
# Observe the Original String
print('Converted String is =', Str1.ljust(30, '='))
print('Original String is =', Str1)
# Performing directly
Str4 = 'Tutorial Gateway'.ljust(30, '*')
print("Justifying Left with '*' using is =", Str4)
# Performing with two characters
Str5 = 'Tutorial Gateway'.ljust(30, '+*')
print('Justifying Left with + and * using is =', Str5)
