在Python中更改字符时拆分 [英] Split when character changes in Python
本文介绍了在Python中更改字符时拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个字符串.
6#666#665533999
我想将其解析为多个小字符串(或直到字符更改),然后忽略#
,以便像电话的拨号盘一样替换6 = M or 666 = O or 9 = W
.
And I want to parse it into multiple small strings(or until the character changes) and ignoring the #
so that I can substitute 6 = M or 666 = O or 9 = W
just like a phone's dial pad.
6#666#665533999 -> 6, 666, 66, 55, 33, 999
所以我用split('#')
方法删除了#
并且不知道下一步该怎么做.对此吗?
So I used the split('#')
method to remove the #
and can't figure out what to do next.I have tried brute force methods which solves it to a certain extent but is there an easier or more elegant solution to this?
推荐答案
使用 itertools.groupby
:
>>> c = "6#666#665533999"
>>> ["".join(g) for k, g in groupby(c) if k != '#']
['6', '666', '66', '55', '33', '999']
然后有一个字典,将这些集合中的每一个映射到拨号盘中的一个字符.
Then have a dictionary which maps each of these sets to a character in the dial pad.
cmap = {'77': 'Q', '9999': 'Z'} # And so forth..
这篇关于在Python中更改字符时拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文