import re def encode(string1): #print("string1: " + string1) regex = re.compile(r"(?=((\w+?)\2+))") m = regex.findall(string1) if m: l = sorted(m, reverse=True, key=lambda t: len(t[0])) #print(l[0]) repeats, repeat = l[0] strings = [string1.split(repeats)[0], repeats, string1.split(repeats)[1]] #print("repeat: " + repeats + repeat) #print(strings) if m: count = repeats.count(repeat) if re.search(r'(.+)\1+', repeats): if count == 1: return encode(strings[0]) + "[" + encode(repeat) + "]" + encode(strings[2]) else: return encode(strings[0]) + str(count) + "[" + encode(repeat) + "]" + encode(strings[2]) else: if count == 1: return encode(strings[0]) + "[" + repeat + "]" + encode(strings[2]) else: return encode(strings[0]) + str(count) + "[" + repeat + "]" + encode(strings[2]) else: return string1 while True: s1 = input("Enter a string: ") if not s1: break print(encode(s1))