How to replace some string with capturing group in Python 3?
Question: 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.


Answer: 
    >>> re.sub('<(.+)>', '[\\1]', '<age>')
    '[age]'
    

Double `\\` is used to escaping the `\`, or else `\1` will be recognised as
`\x01`.  
Brackets `()` are used as a capturing group.

You can use multiple capturing groups like this:

    
    
    >>> re.sub('<(.+)=+(.*)>', '[\\1: \\2]', '<age=5>')
    '[age: 5]'
    

