Python 程序拆分加入连续的相似字符
当需要拆分连接的性质相似的连续字符时,使用'groupby'方法和'join'方法。
示例
下面是相同的演示
from itertools import groupby
my_string = 'pppyyytthhhhhhhoooooonnn'
print("字符串是:")
print(my_string)
my_result = ["".join(grp) for elem, grp in groupby(my_string)]
print("结果是:")
print(my_result)输出结果The original string is : pppyyytthhhhhhhooonnn The resultant split string is : ['ppp', 'yyy', 'tt', 'hhhhhhh', 'ooo', 'nnn']
解释
所需的包被导入到环境中。
定义了一个字符串并显示在控制台上。
字符串被迭代并使用“groupby”方法进行排序。
它被转换为一个列表,并分配给一个变量。
这在控制台上显示为输出。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下