的输出重新分割在python中对m没有意义

2024-09-27 23:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

print (re.split(r'[a-fA-F]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M))
print (re.split(r'[a-fA-Z]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M))
print (re.split(r'\d*','sdfsfdsfds123212fdsf2'))
print (re.split(r'\d','sdfsfdsfds123212fdsf2'))
print (re.split(r'\w+','dsfsf sdfdsf sdfsdf sfsfd'))

['', 'inqw', 'nl', 'sk', 'jri', 'w', 's', 'S', '', '', 'dsafsafasa']
['', 'inqw', 'nl', 'sk', 'jri', 'w', 's', '', '', '', 'ddsafsafasa']
['sdfsfdsfds', 'fdsf', '']
['sdfsfdsfds', '', '', '', '', '', 'fdsf', '']
['', ' ', ' ', ' ', '']

我觉得这里的输出很奇怪。分割字符串的模式有时会在输出列表中变为“”,但有时会消失。在


Tags: renlfasksplitprintsdfsdfdsfsf
3条回答

The pattern that split the string are turned to '' in the output list sometimes, but disappear other time.

不,模式(或它匹配的内容)永远不会包含在输出中。这些''是匹配之间的。因为这就是re.split所做的。你的例子:

>>> re.split(r'\d','sdfsfdsfds123212fdsf2')
['sdfsfdsfds', '', '', '', '', '', 'fdsf', '']

按数字拆分,子字符串'123212'有六个数字,因此它们之间有五个空字符串。这就是为什么输出中有五个空字符串。在

首先,您实际上提供了maxsplit=10参数,而不是flags=re.I|re.

其次,分隔符是而不是变成'';这是分隔符之间的字符串

>>> re.split(r':', 'foo:bar::baz:')
['foo', 'bar', '', 'baz', '']

请注意两个分隔符之间的'',并且在末尾。在

分隔符本身在结果中是而不是,除非正则表达式包含捕获组((...)):

^{pr2}$

第三:尽管r'\d*'通常在字符串的开头、字符串的结尾、每个字符之间的匹配,当前只有非零长度的匹配被re.split考虑,因此该模式的行为类似于r\d+。但是,这种行为可能会在Python3.6及更高版本中发生更改,并在Python 3.5上发出警告FutureWarning: split() requires a non-empty pattern match.。在

输出并不奇怪,它是有意的。From the docs

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']

That way, separator components are always found at the same relative indices within the result list.

强调了为什么要这样做。这同样适用于字符串内的“空”序列和非捕获分隔符。基本上,在分隔符之前和之后都有内容-即使没有捕获分隔符,并且其中任何一个内容都是空的。类似的方法str.splitactually does the same。在

如果知道分隔符,就可以始终重建初始字符串。捕获分隔符并连接,或在连接时插入分隔符是等效的。''.join(re.split('(%s)' % sep, ':::words::words:::')) == sep.join(re.split('%s' % sep, ':::words::words:::'))

相关问题 更多 >

    热门问题