在Python字符串的最后一个分隔符上分割?

问题:在Python字符串的最后一个分隔符上分割?

对于在字符串中最后一次出现定界符时拆分字符串的建议Python惯用法是什么?例:

# 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表示末尾的末尾。如何才能做到这一点?

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?


回答 0

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

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

str.rsplit()可让您指定拆分次数,而str.rpartition()仅拆分一次,但始终返回固定数量的元素(前缀,定界符和后缀),并且对于单个拆分情况而言更快。

演示:

>>> 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()将最大值作为第二个参数,您可以仅分割最右边的出现。

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

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.


回答 1

您可以使用rsplit

string.rsplit('delimeter',1)[1]

从反向获取字符串。

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.


回答 2

我只是为了好玩而做

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

警告:请参阅下面的第一个评论,此答案可能会出错。

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.