2016-12-27 116 views
0

内置的<string>.split()过程工作仅使用空格拆分字符串。更好的拆分字符串方法 -​​ 由多个字符拆分

我想定义一个过程split_string,它接受两个输入:要分割的字符串和包含所有被认为是分隔符的字符的字符串。

该过程应该返回一个字符串列表,这些字符串将列表中的字符打断了源字符串。

def split_string(source,list): 
    ... 

>>> print split_string("This is a test-of the,string separation-code!",",!-") 
['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code'] 
+3

“内置的.split()过程仅使用空格来分割字符串。”这是事实错误的。如果你没有提供参数,那么它将使用空格。但是,如果你这样做,它将使用该参数作为分隔符。 – DeepSpace

+0

另外,split_string('abcd','bc')'的输出是什么? – DeepSpace

回答

1

re.split()作品:

>>> import re 
>>> s = "This is a test-of the,string separation-code!" 
>>> re.split(r'[ \-\,!]+', s) 

['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code', ''] 

在你的情况下搜索词似乎更加有用:

>>> re.findall(r'[\w']+', s) 
['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code'] 
1

这里您可以重复使用的功能 - 这也逃脱特殊字符:

def escape_char(char): 
    special = ['.', '^', '$', '*', '+', '?', '\\', '[', ']', '|'] 
    return '\\{}'.format(char) if char in special else char 

def split(text, *delimiters): 
    return re.split('|'.join([escape_char(x) for x in delimiters]), text) 

它不会自动删除空条目,例如:

>>> split('Python, is awesome!', '!', ',', ' ') 
['Python', '', 'is', 'awesome', '']