import remy_strings = ["po box 12 34 5 heisenburg 902 rr 15", "po box 12 59 76","po box 56 56 barry 56 87","barry box 56 87"]p = re.compile(r'\b(po\s+box\s*)(\d+(?:\s+\d+)+)')for s in my_strings: print(s, ' => ', p.sub(lambda x: f"{x.group(1)}{''.join(c for c in x.group(2).split())}", s))
Standard input is empty
po box 12 34 5 heisenburg 902 rr 15 => po box 12345 heisenburg 902 rr 15 po box 12 59 76 => po box 125976 po box 56 56 barry 56 87 => po box 5656 barry 56 87 barry box 56 87 => barry box 56 87
The brand new service which powers Ideone!
Widget for compiling and running the source code in a web browser!