如何简化此功能?

han*_*nah 1 python

有没有办法简化这个功能?具体来说,我想用更少的缩进行重写它.

# split string (first argument) at location of separators (second argument, should be a string)
def split_string(text, separators):
    text = ' ' + text + ' '
    words = []
    word = ""
    for char in text:
        if char not in separators:
            word += char
        else:
            if word:
                words.append(word)
            word = ""
    if not words:
        words.append(text)
    return words
Run Code Online (Sandbox Code Playgroud)

era*_*ran 6

尝试使用re.split,例如:

re.split('[%s]' % (separators),string)
Run Code Online (Sandbox Code Playgroud)

将[]创建一个正则表达式字符类分割上.

  • 很好的解决方案,除非你应该转义分隔符中的字符,以防它们是reqex限定符:`re.split('[%s]'%'\\'.join(separators),text)` (2认同)