Python 更好的拆分字符串方法-按多个字符拆分
内置的Python 更好的拆分字符串方法-按多个字符拆分,python,python-2.7,split,Python,Python 2.7,Split,内置的.split()过程只使用空格分割字符串 我想定义一个过程split_string,它接受两个输入:要拆分的字符串和包含所有被视为分隔符的字符的字符串 该过程应返回一个字符串列表,这些字符串按列表中的字符将源字符串拆分 def split_string(source,list): ... >>> print split_string("This is a test-of the,string separation-code!",",!-") ['This', '
.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']
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']
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']
这是一个可以重用的函数,它还可以转义特殊字符:
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', '']
这是一个可以重用的函数,它还可以转义特殊字符:
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', '']
“内置的.split()过程只使用空格分割字符串。”这实际上是错误的。如果您没有为它提供参数,那么它将使用空格。但是如果您这样做,它将使用该参数作为分隔符。另外,split_string('abcd','bc')
的输出是什么?“内置的.split()过程只使用空格分割字符串。”这实际上是错误的。如果您没有为它提供参数,那么它将使用空格。但是如果您这样做,它将使用该参数作为分隔符。另外,split_string('abcd','bc')
的输出是什么?