python partition函数_Python string rpartition()用法及代码示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值