1

この関数を単純化する方法はありますか? 具体的には、インデントの行数を減らして書き直したいと思っています。

# 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
4

4 に答える 4

6

たとえば、re.splitを使用してみてください。

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

[]、分割する正規表現文字クラスを作成します。

于 2013-04-25T21:05:07.407 に答える