在字符串中 last 出现的分隔符处拆分字符串的推荐 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
表示最后一个。如何做到这一点?
最佳答案
使用 .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()
一个最大值作为第二个参数,您可以只拆分最右边的事件。
如果您只需要最后一个元素,但分隔符可能不存在于输入字符串中或者是输入中的最后一个字符,请使用以下表达式:
# last element, or the original if no `,` is present or is the last character
s.rsplit(',', 1)[-1] or s
s.rpartition(',')[-1] or s
如果分隔符即使是最后一个字符也需要消失,我会使用:
def last(string, delimiter):
"""Return the last element from string, after the delimiter
If string ends in the delimiter or the delimiter is absent,
returns the original string without the delimiter.
"""
prefix, delim, last = string.rpartition(delimiter)
return last if (delim and last) else prefix
这使用了 string.rpartition()
仅当分隔符存在时才将分隔符作为第二个参数返回,否则返回空字符串。
https://stackoverflow.com/questions/15012228/