Python 中的 rsplit() 函数通过从右端开始并使用指定的分隔符分割原始字符串,返回一个字符串列表。
str.rsplit([separator [, maxsplit]]) #where separator may be a character,symbol,or space
rsplit() 函数接受两个参数。如果未提供分隔符参数,它将把任何空白字符(空格、换行符等)作为分隔符。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 分隔符 | 它是一个分隔符。字符串将在指定的分隔符处进行分割。 | 可选 |
| maxsplit | maxsplit 定义了最大分割次数。 maxsplit 的默认值为 -1。 |
可选 |
返回值为一个字符串列表。如果分割次数为 maxsplit,则输出列表中将有 maxsplit+1 个项。如果未找到指定的分隔符,则返回一个以整个字符串作为元素的列表。
| 输入 | 返回值 |
|---|---|
| string | 字符串列表 |
string= 'Hii How are you'
# splits at space
print(string.rsplit())
fruits= 'apple, orange, grapes'
# splits at ','
print(fruits.rsplit(', '))
# Splits at ':' but not exist so return original
print(fruits.rsplit(':'))
输出
['Hii', 'How', 'are', 'you'] ['apple', 'orange', 'grapes'] ['apple, orange, grapes']
fruits= 'apple, orange, grapes, strawberry'
# maxsplit: 2
print(fruits.split(', ', 2))
# maxsplit: 1
print(fruits.split(', ', 1))
# maxsplit: 5
print(fruits.split(', ', 5))
# maxsplit: 0
print(fruits.split(', ', 0))
输出
['apple, orange', 'grapes', 'strawberry'] ['apple, orange, grapes', 'strawberry'] ['apple', 'orange', 'grapes', 'strawberry'] ['apple, orange, grapes, strawberry']