Khi cần tách các ký tự liên tiếp giống nhau đã được gộp, ta dùng phương thức groupby và join.
Ví dụ
from itertools import groupby
my_string = 'pppyyytthhhhhhhoooooonnn'
print("The string is:")
print(my_string)
my_result = ["".join(grp) for elem, grp in groupby(my_string)]
print("The result is:")
print(my_result)
Đầu ra
The original string is: pppyyytthhhhhhhooonnn The resultant split string is: ['ppp', 'yyy', 'tt', 'hhhhhhh', 'ooo', 'nnn']
Giải thích
- Nhập
itertools.groupby. - Định nghĩa chuỗi, hiển thị.
- Lặp chuỗi, nhóm bằng
groupby. - Chuyển thành list, gán biến, hiển thị.