Python中的rpartition()函数将给定的字符串分为三部分。 rpartition()从右侧开始查找分隔符,直到找到分隔符,然后返回一个元组,其中包含分隔符之前的字符串部分,字符串的参数以及分隔符之后的部分。
用法:
string.rpartition(separator)
参数:
separator - separates the string at the first occurrence of it.
返回值:
- 如果在字符串中找到了分隔符参数,它将返回分隔符之前的字符串部分,分隔符参数本身以及分隔符之后的部分。
- 它返回两个空字符串,如果在字符串中找不到分隔符,则返回给定的字符串。
异常:
If separator argument is not supplied, it will throw TypeError.
代码1:
# Python3 code explaining rpartition()
# String need to split
string1 = "Geeks@for@Geeks@is@for@geeks"
string2 = "Ram is not eating but Mohan is eating"
# Here '@' is a separator
print(string1.rpartition('@'))
# Here 'is' is seperator
print(string2.rpartition('is'))
输出:
('Geeks@for@Geeks@is@for', '@', 'geeks') ('Ram is not eating but Mohan ', 'is', ' eating')
代码2:
# Python3 code explaining rpartition()
# String need to split
string = "Sita is going to school"
# Here 'not' is a separator which is not
# present in the given string
print(string.rpartition('not'))
输出:
('', '', 'Sita is going to school')
代码3: TypeError
# Python3 code explaining TypeError
# in rpartition()
str = "Bruce Waine is Batman"
# Nothing is passed as separator
print(str.rpartition())
输出:
Traceback (most recent call last): File "/home/e207c003f42055cf9697001645999d69.py", line 7, in print(str.rpartition()) TypeError:rpartition() takes exactly one argument (0 given)
代码4: ValueError
# Python3 code explaining ValueError
# in rpartition()
str = "Bruce Waine is Batman"
# Nothing is passed as separator
print(str.rpartition(""))
输出:
Traceback (most recent call last): File "/home/c8d9719625793f2c8948542159719007.py", line 7, in print(str.rpartition("")) ValueError:empty separator
相关用法
注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 Python String | rpartition()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。