Trying to understand Python re.replace I was trying to switch groups by index or by name but encountered a problem using re to do that.
let's say: line = '23 24" #and I want to get '242 231'
nline = re.sub(r"(\d+) (\d+)", r"\2 \1", line)
#This will result '24 23'
but if I add numbers following the index - I will get invalid index: nline = re.sub(r"(\d+) (\d+)", r"\22 \11", line)
I have tried to use name group - but failed to make it work: nline = re.sub(r"(?P\d+) (?P\d+)", r"\s2 \f1", line)
line = '23 24"
#Trial#1
nline = re.sub(r"(\d+) (\d+)", r"\22 \11", line)
#Trial #2
nline = re.sub(r"(?P<f>\d+) (?P<s>\d+)", r"\s2 \f1", line)
I would like to know how to replace a group index followed by another number
and how to use group name in the back reference