跳到主要内容

Python 字符串 rstrip() 方法

rstrip() 方法返回一个副本,其中删除了字符串尾部的字符(基于传递的字符串参数)。

示例

title = 'Python Programming '

# 从 title 中移除尾部空白
result = title.rstrip()
print(result)

# 输出: Python Programming

String rstrip() 的语法

rstrip() 的语法是:

string.rstrip([chars])

rstrip() 参数

  • chars(可选)- 指定要移除的尾部字符集的字符串。

rstrip() 方法根据参数(指定要删除的字符集的字符串)从右侧移除字符。

如果没有提供 chars 参数,则从字符串中移除所有右侧的空白字符。

rstrip() 返回值

rstrip() 返回一个副本,其中尾部字符被剥离。

chars 参数中的所有字符组合都会从字符串的右侧被移除,直到第一个不匹配。

示例:rstrip() 的工作原理

random_string = 'this is good '

# 移除尾部空白
print(random_string.rstrip())

# 'si oo' 不是尾部字符,所以没有移除
print(random_string.rstrip('si oo'))

# 在 'sid oo' 中,'d oo' 是尾部字符,字符串中的 'ood' 被移除
print(random_string.rstrip('sid oo'))
website = 'www.mashangxue123.com/'

print(website.rstrip('m/.'))

输出

this is good
this is good
this is g
www.mashangxue123.co