import re
text = 'section{First} section{second}'
p = re.compile('section{([^}]*)}')
print 'before substitution: ', text
print 'after substitution: ', p.sub(r'subsection{\1}', text)
结果:
before substitution: section{First} section{second}
after substitution: subsection{First} subsection{second}
为什么第二部分也会相应替换?我怎样才能用子节替换第一节?如何在替换字符串中用{First}替换{First}和{Second}?