import re text = """ Tumble Trouble Twwixt Two Towns! Was the Moon soon in the Sea Or soon in the sky? Nobody really knows YET. """ print(re.compile(r"((\w+)\2)(?=.*?\1)").sub('{\g<1>}', text.rstrip()))
Standard input is empty
Tumble Trouble Twwixt Two Towns! Was the M{oo}n soon in the Sea Or soon in the sky? Nobody really knows YET.