I'm a Python beginner. I'd like to find <(.+?)> from a string, and replace it with [\1]. For example,
string_input = '<age>'
string_output = '[age]'
I tried,
import re
string = '<age>'
re.sub('<.+?>, '[' + \1 + ']', string)
But it failed.
I'm a Python beginner. I'd like to find <(.+?)> from a string, and replace it with [\1]. For example,
string_input = '<age>'
string_output = '[age]'
I tried,
import re
string = '<age>'
re.sub('<.+?>, '[' + \1 + ']', string)
But it failed.
You best access the capturing group by using \g<>, so since you only have one capturing group, you use \g<1>.
In [1]: re.sub(r'<(.+?)>', '[\g<1>]', '<age>')
Out[1]: '[age]'
The advantage of using \g<> is that you can also give names to your capturing groups and then access them by the names again, for example:
In [2]: re.sub(r'<(?P<content>.+?)>', '[\g<content>]', '<age>')
Out[2]: '[age]'