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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15012228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:05:53  来源:igfitidea点击:

Splitting on last delimiter in Python string?

pythonstringlistparsingsplit

提问by

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

在字符串中最后一次出现分隔符时拆分字符串的推荐 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']

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

mysplit接受第二个参数,即要拆分的分隔符的出现。就像在常规列表索引中一样,-1意味着最后一个。如何才能做到这一点?

采纳答案by Martijn Pieters

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

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

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.

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

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.

两种方法都从字符串的右侧开始拆分;通过str.rsplit()将最大值作为第二个参数,您可以只拆分最右侧的事件。

回答by ViKiG

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.

注意:请参阅下面的第一条评论,此答案可能出错。

回答by Vivek Ananthan

You can use rsplit

您可以使用 rsplit

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

To get the string from reverse.

从反向获取字符串。