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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。