python - 在 python 中用空格重新拆分

标签 python regex split

我有一串看起来像这样的文本:

'                     19,301         14,856        18,554'

空格在哪里。

我试图在空白处拆分它,但我需要保留所有空白作为新列表中的一项。像这样:

['                     ', '19,301','        ', '14,856', '        ', '18,554']

我一直在使用下面的代码:

re.split(r'( +)(?=[0-9])', item)

它返回:

['', '                     ', '19,301', '        ', '14,856', '        ', '18,554']

请注意,它总是在列表的开头添加一个空元素。放弃它很容易,但我真的很想了解这里发生了什么,所以我可以获得代码来一致地处理事情。谢谢。

最佳答案

使用re.split 方法时,如果捕获组在字符串的开头匹配,则为“result will start with an empty string”。这样做的原因是 join 方法的行为与 split 方法相反。

对于您的情况可能没有多大意义,因为分隔符匹配的大小不同,但是如果您考虑分隔符是 | 字符的情况并且您想要执行加入它们,加上额外的空字符串就可以了:

>> item = '|19,301|14,856|18,554'
>> items = re.split(r'\|', item)
>> print items
['', '19,301', '14,856', '18,554']
>> '|'.join(items)
'|19,301|14,856|18,554'

但如果没有它,初始管道将丢失:

>> items = ['19,301', '14,856', '18,554']
>> '|'.join(items)
'19,301|14,856|18,554'

关于python - 在 python 中用空格重新拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005907/

相关文章:

python - 最小化 QTreeWidgetItem 中 QTextEdit 的大小

javascript - 替换除第一个以外的所有匹配项

html - 编写 HTML 解析器时借用的值不够长

python - 哪种更好的方式来写出Python的错误

python - 将 python 前瞻断言正则表达式转换为有效的 Golang

Python x-www-form-urlencoded POSTing : cannot find attributes

php - 从 JSON 字符串中删除所有不必要的空格(在 PHP 中)

java - String 的 split 函数没有

r - 根据 OID 按类别拆分数据帧

python - 将文档逐行追加到列表中