在Python字符串中的最后一个分隔符上分割? [英] Splitting on last delimiter in Python string?

查看:469
本文介绍了在Python字符串中的最后一个分隔符上分割?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在字符串中最后一个出现定界符的 last 上建议拆分字符串的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采用第二个参数,该参数是要分割的分隔符的出现.与常规列表索引一样,-1表示末尾.该怎么办?

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?

推荐答案

使用 .rsplit() .rpartition() 代替:

Use .rsplit() or .rpartition() instead:

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

str.rsplit()可让您指定拆分次数,而str.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.

演示:

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

这两个方法都从字符串的右侧开始拆分;通过给str.rsplit()一个最大值作为第二个参数,您就可以拆分出最右边的出现次数.

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.

这篇关于在Python字符串中的最后一个分隔符上分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆