📜  Python字符串 | rpartition()

📅  最后修改于: 2022-05-13 01:55:40.019000             🧑  作者: Mango

Python字符串 | rpartition()

Python中的rpartition()函数将给定的字符串分成三部分。 rpartition() 从右侧开始寻找分隔符,直到找到分隔符并返回一个元组,其中包含分隔符之前的部分字符串、字符串的参数和分隔符之后的部分。

句法 :

string.rpartition(separator)

参数 :

separator -  separates the string at the first occurrence of it.

返回值:

  1. 它返回分隔符之前的字符串部分、分隔符参数本身以及分隔符之后的部分(如果在字符串中找到分隔符参数)。
  2. 它返回两个空字符串,如果在字符串。

例外 :

If separator argument is not supplied, it will throw TypeError.

代码#1:

Python3
# 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 separator
print(string2.rpartition('is'))


Python3
# 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'))


Python3
# Python3 code explaining TypeError
# in rpartition()
 
str = "Bruce Waine is Batman"
 
# Nothing is passed as separator
print(str.rpartition())


Python3
# Python3 code explaining ValueError
# in rpartition()
 
str = "Bruce Waine is Batman"
 
# Nothing is passed as separator
print(str.rpartition(""))


输出 :

('Geeks@for@Geeks@is@for', '@', 'geeks')
('Ram is not eating but Mohan ', 'is', ' eating')

代码#2:

Python3

# 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:类型错误

Python3

# 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

# 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