python字符串的定界符可以是_在Python字符串中的最后一个分隔符上分割?

What's the recommended Python idiom for splitting a string on the last occurrence of the delimiter in the string? example:

# instead of regular split

>> s = "a,b,c,d"

>> s.split(",")

>> ['a', 'b', 'c', 'd']

# ..split only on last occurrence of ',' in string:

>>> s.mysplit(s, -1)

>>> ['a,b,c', 'd']

mysplit takes a second argument that is the occurrence of the delimiter to be split. Like in regular list indexing, -1 means the last from the end. How can this be done?

解决方案s.rsplit(',', 1)

s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"

>>> s.rsplit(',', 1)

['a,b,c', 'd']

>>> s.rsplit(',', 2)

['a,b', 'c', 'd']

>>> s.rpartition(',')

('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值