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

原文由 user248237 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 368
2 个回答

使用 .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() 仅当分隔符存在时才将分隔符作为第二个参数返回,否则返回空字符串。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以使用 rsplit

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

从反向获取字符串。

原文由 Wickkiey 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题