在Python中拆分带有多个分隔符的字符串

时间:2011-02-14 23:42:13

标签: python string split delimiter

我在网上找到了一些答案,但我没有使用正则表达式的经验,我相信这就是我需要的。

我有一个字符串需要用';'分割要么 ', ' 也就是说,它必须是分号或逗号后跟空格。不带尾随空格的单个逗号应保持不变

示例字符串:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"
应将

拆分为包含以下内容的列表:

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') 

5 个答案:

答案 0 :(得分:637)

幸运的是,Python内置了这个:)

import re
re.split('; |, ',str)

更新:
发表评论:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

答案 1 :(得分:160)

执行str.replace('; ', ', '),然后执行str.split(', ')

答案 2 :(得分:86)

对于任何可迭代的分隔符,使用正则表达式,这是一种安全的方法:

>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regexPattern = '|'.join(map(re.escape, delimiters))
>>> regexPattern
'a|\\.\\.\\.|\\(c\\)'
>>> re.split(regexPattern, example)
['st', 'ckoverflow ', ' is ', 'wesome', " isn't it?"]

re.escape允许自动构建模式并使分隔符很好地转义。

以下是此解决方案作为复制粘贴乐趣的功能:

def split(delimiters, string, maxsplit=0):
    import re
    regexPattern = '|'.join(map(re.escape, delimiters))
    return re.split(regexPattern, string, maxsplit)

如果您要经常使用相同的分隔符进行分割,请事先按照描述编译正则表达式并使用RegexObject.split

答案 3 :(得分:48)

回应Jonathan上面的回答,这似乎只适用于某些分隔符。例如:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

通过将分隔符放在方括号中,它似乎更有效。

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

答案 4 :(得分:26)

这就是正则表达式的样子:

import re
# "semicolon or (a comma followed by a space)"
pattern = re.compile(r";|, ")

# "(semicolon or a comma) followed by a space"
pattern = re.compile(r"[;,] ")

print pattern.split(text)