在 Python 字符串中的最后一个分隔符上拆分? [英] Splitting on last delimiter in Python string?

查看:47
本文介绍了在 Python 字符串中的最后一个分隔符上拆分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于在字符串中最后 次出现分隔符时拆分字符串的推荐 Python 习语是什么?例子:

# 代替常规拆分>>s = "a,b,c,d">>s.split(",")>>['A B C D']# ..split 仅在字符串中最后一次出现 ',' 时:>>>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() 一个最大值作为第二个参数,你可以只拆分最右边的出现.

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?

解决方案

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.

这篇关于在 Python 字符串中的最后一个分隔符上拆分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆