How to replace an re match with a transformation of that match?

前端 未结 2 503
长情又很酷
长情又很酷 2021-01-13 09:02

For example, I have a string:

The struct-of-application and struct-of-world

With re.sub

2条回答
  •  梦谈多话
    2021-01-13 09:54

    Use a function for the replacement

    s = 'The struct-of-application and struct-of-world'
    p = re.compile('((\w+-)+\w+)')
    def replace(match):
        return 'http://{}'.format(match.group())
        #for python 3.6+ ... 
        #return f'http://{match.group()}'
    
    >>> p.sub(replace, s)
    
    'The http://struct-of-application and http://struct-of-world'
    >>>
    

提交回复
热议问题