result = re.sub("(d+) (w+)", r"2 1") result = re.sub("(?<number>d+) (?<word>w+)", r"g<word> g<number>")