Skip to main content
 首页 » 编程设计

python之我怎样才能简化这个功能

2025年05月04日9jirigala

有什么办法可以简化这个功能吗?具体来说,我想用更少的缩进行重写它。

# 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 

请您参考如下方法:

尝试使用 re.split ,例如:

re.split('[%s]' % (separators),string) 

[] 创建一个正则表达式字符类来拆分。