如何用python分割这个字符串?
我的字符串类似于此示例: “AAABBBCDEEEEBBBAA”
字符串中可以包含任何字符。
我想将其拆分为一个列表,例如: ['AAA','BBB','C','D','EEEE','BBB','AA']
因此相同字符的每个连续延伸都会进入拆分列表的单独元素。
我知道我可以迭代字符串中的字符,检查每个 i 和 i-1 对是否包含相同的字符等。但是有没有更简单的解决方案?
I have strings that look like this example:
"AAABBBCDEEEEBBBAA"
Any character is possible in the string.
I want to split it to a list like:
['AAA','BBB','C','D','EEEE','BBB','AA']
so every continuous stretch of the same characters goes to separate element of the split list.
I know that I can iterate over characters in the string, check every i and i-1 pair if they contain the same character, etc. but is there a more simple solution out there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是解决问题的另一种方法:
Just another way of soloving your problem :
我们可以使用正则表达式:
或者,我们可以使用
itertools.groupby
。timeit
显示正则表达式更快(对于这个特定字符串)(Python 2.6,Python 3.1)。但Regex毕竟是字符串专用的,而groupby
是一个通用函数,所以这并不意外。We could use Regex:
Alternatively, we could use
itertools.groupby
.timeit
shows Regex is faster (for this particular string) (Python 2.6, Python 3.1). But Regex is after all specialized for string, andgroupby
is a generic function, so this is not so unexpected.并通过正常的字符串操作
And by normal string manipulation