有没有办法简化这个功能?具体来说,我想用更少的缩进行重写它.
# 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)
尝试使用re.split,例如:
re.split('[%s]' % (separators),string)
Run Code Online (Sandbox Code Playgroud)
将[]创建一个正则表达式字符类分割上.