Python:如何在字符串分割中包含分隔符?

11

我想要分割一个包含多个分隔符的字符串,并且保留分隔符在结果列表中。我认为这是解析任何公式的初始步骤中的有用操作,而且我怀疑Python会有一个不错的解决方案。

有人曾经在Java中问过类似的问题,链接在这里

例如,一个典型的分割操作看起来像这样:

>>> s='(twoplusthree)plusfour'
>>> s.split(f, 'plus')
['(two', 'three)', 'four']

但是我正在寻找一种好的方法来添加加号(或保留它):

['(two', 'plus', 'three)', 'plus', 'four']
最终,我希望能够针对每个运算符和括号执行此操作,因此如果有一种方法可以获取

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

一次完成所有操作,那就更好了。

5个回答

14
您可以使用Python的re模块来实现这一点。
import re
s='(twoplusthree)plusfour'
list(filter(None, re.split(r"(plus|[()])", s)))

如果你只需要迭代器,可以省略列表。


4
import re
s = '(twoplusthree)plusfour'
l = re.split(r"(plus|\(|\))", s)
a = [x for x in l if x != '']
print a

输出:

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

4

这里有一个使用 re.split 的简单方法:

import re

s = '(twoplusthree)plusfour'
re.split('(plus)',  s)

输出:

['(two', 'plus', 'three)', 'plus', 'four']

re.splitstring.split非常相似,只是不使用字面分隔符而是传递一个正则表达式模式。关键是将()放在模式周围,这样它就会被提取为一组。

请注意,如果存在两个连续的分隔符模式,则会产生空字符串。


0

这里我正在将一个字符串在第一次出现字母字符的位置进行分割:

def split_on_first_alpha(i):
    #i="3.5 This is one of the way"
    split_1=re.split(r'[a-z]',i,maxsplit=1, flags=re.IGNORECASE)
    find_starting=re.findall(r'[a-z]',i,flags=re.IGNORECASE)
    split_1[1]=find_starting[0]+split_1[1]
    return split_1

0

这个线程很老了,但由于它是谷歌的首要结果,我想添加一下:

如果你不想使用正则表达式,有一种更简单的方法来做。基本上只需调用split函数,但仅在最后一个标记之外恢复分隔符。

def split_keep_deli(string_to_split, deli):
    result_list = []
    tokens = string_to_split.split(deli)
    for i in xrange(len(tokens) - 1):
        result_list.append(tokens[i] + deli)
    result_list.append(tokens[len(tokens)-1])
    return  result_list

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接