What should I do if I want to use the matching string in re.sub()
as the replacement string?
I follow the method described in the document, but it does not print well.
import re
if__name__=='__main__':
tmp = re.sub('(a|b)', '\1\n', 'aiueobcd')
print(tmp)
a
iueob
cd
re--- Regular Expression Manipulation—Python 3.9.4 Documentation
Python|Replace a string that matches a regular expression with a new string (Pattern.sub, Pattern.subn)
p python --version
Python 3.9.5
Thank you for your cooperation.
python regular-expression
We recommend using the Raw string in Metropolis's comment, but if you do not want to use the Raw string,
#tmp=re.sub('(a|b)', '\1\n', 'aiueobcd')
tmp = re.sub('(a|b)', '\\1\n', 'aiueobcd')
as
© 2023 OneMinuteCode. All rights reserved.