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

在字符串中 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/

相关文章:

python - 如何在 Python 中创建对象的副本?

mysql - MySQL 服务器和 MySQL 客户端有什么区别

linux - 使用 unix 命令 "watch"的颜色?

linux - 如何通过将其内存存储到磁盘并稍后恢复它来在 Linux 中 "hibernate"进

python - 如何让 python 的 pprint 返回一个字符串而不是打印?

python - 使用 argparse 需要两个参数之一

linux - SIGINT 与 SIGTERM、SIGQUIT 和 SIGKILL 等其他终止信号

python - 使用 IPython 逐步调试

linux - 如何使用 strace 跟踪子进程?

python - 使用 pandas 绘制相关矩阵