这个问题在这里已经有了答案:
Splitting a string with repeated characters into a list
(4 个回答)
5年前关闭。
这很容易,我就是做不到!在这个例子中,我想要做的就是将下面的字符串分成彼此相邻的相同字母块,例如在下面的例子中:test = "AAATGG", 将被拆分为 "AAA","T","GG"。我一直在尝试不同的方法,下面举一个例子。我很感激你的帮助。
我知道这个想法是遍历字符串,如果下一个字母与当前字母相同,则继续,否则,中断并打印并重新开始,我无法正确实现它。
test = "AAATGG"
TestDict = {}
for index,i in enumerate(test[:-1]):
string = ""
if test[index] == test[index+1]:
string = i + test[index]
else:
break
print string
最佳答案
一种方法是使用 groupby
来自 itertools
:
from itertools import groupby
[''.join(g) for _, g in groupby(test)]
# ['AAA', 'T', 'GG']
关于python - 将字符串拆分为相同字母的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617330/