Python分割字符串,不使用正则表达式且支持多个分隔符

4

我有一个字符串需要在多个字符上进行拆分,不能使用正则表达式。例如,我需要像下面这样的内容:

>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']

有没有类似这样的Python代码?

如果您想避免使用正则表达式,就必须在split中使用replace。这是一份作业吗? - Sully
不,这不是作业。避免使用正则表达式的原因很简单,我实在不太懂正则表达式。 - ewok
我建议尝试一些正则表达式教程(比如这个),因为在Python中使用正则表达式非常有用且易于使用。 - Blin
5个回答

8
如果您需要多个分隔符,re.split 是一个好方法。
如果不使用正则表达式,则除非编写自定义函数,否则无法实现。
以下是这样的一个函数 - 它可能或可能不会做你想要的事情(连续的分隔符会导致空元素):
>>> def multisplit(s, delims):
...     pos = 0
...     for i, c in enumerate(s):
...         if c in delims:
...             yield s[pos:i]
...             pos = i + 1
...     yield s[pos:]
...
>>> list(multisplit('hello there[my]friend', ' []'))
['hello', 'there', 'my', 'friend']

1

不使用正则表达式的解决方案:

from itertools import groupby
sep = ' []'
s = 'hello there[my]friend'
print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k]

我刚刚在这里发布了一个解释 https://dev59.com/onNA5IYBdhLWcg3wL6sc#19211729


1

一种不使用正则表达式的递归解决方案。与其他答案相比,仅使用基本的Python。

def split_on_multiple_chars(string_to_split, set_of_chars_as_string):
    # Recursive splitting
    # Returns a list of strings

    s = string_to_split
    chars = set_of_chars_as_string

    # If no more characters to split on, return input
    if len(chars) == 0:
        return([s])

    # Split on the first of the delimiter characters
    ss = s.split(chars[0])

    # Recursive call without the first splitting character
    bb = []
    for e in ss:
        aa = split_on_multiple_chars(e, chars[1:])
        bb.extend(aa)
    return(bb)

该函数与Python的常规string.split(...)非常相似,但可以接受多个分隔符。

使用示例:

print(split_on_multiple_chars('my"example_string.with:funny?delimiters', '_.:;'))

输出:

['my"example', 'string', 'with', 'funny?delimiters']

0

如果您不担心长字符串,可以使用string.replace()强制所有分隔符相同。以下代码将字符串按-,进行拆分:

x.replace('-', ',').split(',')

如果有多个分隔符,可以采用以下方法:

def split(x, delimiters):
    for d in delimiters:
        x = x.replace(d, delimiters[0])
    return x.split(delimiters[0])

-3

re.split 是这里的正确工具。

>>> string="hello there[my]friend"
>>> import re
>>> re.split('[] []', string)
['hello', 'there', 'my', 'friend']

在正则表达式中,[...] 定义了一个字符类。方括号内的任何字符都将匹配。我在括号之间的空格方式避免了需要转义它们,但是模式 [\[\] ] 也可以工作。
>>> re.split('[\[\] ]', string)
['hello', 'there', 'my', 'friend']

re.DEBUG标志对于re.compile也很有用,因为它会打印出模式将匹配的内容:

>>> re.compile('[] []', re.DEBUG)
in 
  literal 93
  literal 32
  literal 91
<_sre.SRE_Pattern object at 0x16b0850>

(其中32、91、93是分别赋给[]的ASCII值)


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