Python rstrip

Python 的 rstrip 方法用于从字符串的右侧移除指定的字符。默认情况下,它会移除末尾的空白字符并返回一个新字符串。rstrip 字符串函数语法如下所示。

text.rstrip(Chars)
  • Chars: 如果我们省略此参数,它会将空白字符识别为默认参数。要进行修改,请指定要从字符串中移除的字符。

Python rstrip 字符串函数示例

rstrip 方法返回一个字符串的副本,其中末尾的字符已被移除。以下示例集有助于理解此函数。

Str1 = 'Tutorial Gateway         '

Str2 = Str1.rstrip()
print('Delete White sapces on Right Side using it is =', Str2)

# Observe the Original
print('Converted is =', Str1.rstrip())
print('Original is  =', Str1)
      
# Performing it directly
Str3 = '00000000Tutorial Gateway00000000'.rstrip('0')
print("Deleting 0's on Right Side using it is =", Str3)

# Remove Right Side
Str4 = 'Tutorial Gateway+++++*********'.rstrip('+*')
print('Deleting + and * on Right Side using it is =', Str4)
Python RStrip string function

第一个语句使用此 rstrip 函数从变量 Str1 的右侧移除空白字符并打印输出。

下一个 print 语句返回一个新字符串中的输出,而不是更改原始字符串。要更改原始字符串,请编写以下语句。

Str1 = Str1.rstrip()

rstrip 只会移除字符串右侧给定的字符,而忽略左侧的字符。

在下面的 Str3 Python 语句中,我们在两侧都有零。但是,请注意该方法仅移除了右侧的零。

在此 Str4 方法示例代码中,我们使用了两个要从右侧移除的字符(+ 和 *)。