Python string.rstrip() 函数用法

2023-09-17 22:22:45

rstrip() 方法通过删除指定为参数的尾随字符来返回字符串的副本。 如果未提供 character 参数,则会从字符串中删除所有尾随空格。

尾随字符是出现在字符串末尾(字符串最右侧)的字符。

语法:

str.rstrip(characters)

参数:

字符:(可选)要从字符串末尾删除的字符或字符串。

返回值:

一个字符串。

下面的示例演示了 rstrip() 方法。

t
>>> mystr = '     Hello World     '
>>> mystr.rstrip() # removes trailing spaces
'     Hello World '
>>> mystr = '''
Python is 
a programming language
'''
>>> mystr.rstrip()  # removes trailing n
'nPython is na programming language'
>>> mystr = '----Hello World----'
>>> mystr.rstrip('-')  # removes trailing -
'----Hello World'

可以将一个或多个字符指定为要按任意顺序从字符串中删除的字符串,如下所示。

t
>>> '#$2Hello World#$2'.rstrip('$2#')
'#$2Hello World'
>>> 'Hello World#-$2'.rstrip('$2#')
'Hello World#-'
>>> 'www.python114.com.com/'.rstrip('/.') # remove www.
'www.python114.com.com'
>>> 'bcā'.rstrip('ā') # removes Unicode char
'bc'

在上面的示例中,'#$2Hello World#$2'.rstrip('$2#')删除尾随字符"$"、"2"或"#",即使按任何顺序出现也是如此。 但是,Hello World#-$2'.rstrip('$2#')只删除尾随的"$"和"2",因为"-"未指定要删除,因此它停在那里并将其视为一个单词。

想看看你对Python了解多少吗? Start Python Test