Python rjust

Python rjust 方法用于将字符串的右侧或尾部对齐,并用指定的字符填充剩余的宽度。默认情况下,rjust 函数会考虑空格并返回新字符串。

在本节中,我们将通过一个示例讨论如何编写字符串 rjust 函数,其语法如下所示。

String_Value.rjust(Width, Char)
  • 宽度: 字符串的长度。
  • 字符: 如果省略此参数,则它将空白字符视为默认参数。要更改默认值,请指定要在剩余宽度中使用的字符。

Python rjust 方法示例

此字符串函数仅接受单个字符作为其第二个参数。以下示例集将帮助您理解 rjust 函数。

下面的 Str2 语句将字符串变量 Str1 的右侧对齐,用默认的空格填充剩余宽度,并打印输出。

您可能会对空格感到困惑,因此我们在此 Str3 变量中使用了“=”作为第二个参数。此 Python 语句用“=”符号填充剩余宽度。

Python rjust 函数返回一个新字符串,而不是修改原始字符串。要更改原始字符串,请编写以下 方法 语句。

Str1 = Str1.rjust()

rjust 函数只允许单个字符作为第二个参数。让我们看看当我们在 Str4 和 Str5 中使用两个字符(+ 和 *)时会发生什么。

下面的屏幕截图显示它抛出了一个错误,提示:“TypeError: The fill character must be exactly one character long”(类型错误:填充字符必须正好是一个字符长)。

Str1 = 'Tutorial Gateway';

Str2 = Str1.rjust(30)
print('Justifying Right with White sapces is =', Str2)

Str3 = Str1.rjust(30, '=')
print("Justifying Right with '=' using RJust() is =", Str3)

# Observe the Original
print('Converted String is =', Str1.rjust(30, '='))
print('Original String is =', Str1)

# Performing directly
Str4 = 'Tutorial Gateway'.rjust(30, '*')
print("Justifying Right with '*' using RJust() is =", Str4)

# Performing with two characters
Str5 = 'Tutorial Gateway'.rjust(30, '+*')
print('Justifying Right with + and * using RJust() is =', Str5)
rjust Function Example