re.split() 给出列表中的空元素 [英] re.split() gives empty elements in list

查看:32
本文介绍了re.split() 给出列表中的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助解决这个问题:

m = re.split('([A-Z][a-z]+)', 'PeopleRobots')打印(米)

结果:

['', '人', '', '机器人', '']

为什么列表中有空元素?

解决方案

根据 重新拆分文档:

<块引用>

如果分隔符中有捕获组并且匹配在字符串开头,结果将以空字符串开头.这字符串的结尾也是如此:

如果您想获得 PeopleRobots,请使用 re.findall:

<预><代码>>>>re.findall('([A-Z][a-z]+)', 'PeopleRobots')['人','机器人']

您可以省略分组:

<预><代码>>>>re.findall('[A-Z][a-z]+', 'PeopleRobots')['人','机器人']

please help with this case:

m = re.split('([A-Z][a-z]+)', 'PeopleRobots')
print (m)

Result:

['', 'People', '', 'Robots', '']

Why does the list have empty elements?

解决方案

According to re.split documentation:

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:

If you want to get People and Robots, use re.findall:

>>> re.findall('([A-Z][a-z]+)', 'PeopleRobots')
['People', 'Robots']

You can omit grouping:

>>> re.findall('[A-Z][a-z]+', 'PeopleRobots')
['People', 'Robots']

这篇关于re.split() 给出列表中的空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆