Python replace string pattern with output of function

后端 未结 4 597
臣服心动
臣服心动 2020-11-27 18:24

I have a string in Python, say The quick @red fox jumps over the @lame brown dog.

I\'m trying to replace each of the words that begin with @

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 18:50

    I wasn't aware you could pass a function to a re.sub() either. Riffing on @Janne Karila's answer to solve a problem I had, the approach works for multiple capture groups, too.

    import re
    
    def my_replace(match):
        match1 = match.group(1)
        match2 = match.group(2)
        match2 = match2.replace('@', '')
        return u"{0:0.{1}f}".format(float(match1), int(match2))
    
    string = 'The first number is 14.2@1, and the second number is 50.6@4.'
    result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string)
    
    print(result)
    

    Output:

    The first number is 14.2, and the second number is 50.6000.

    This simple example requires all capture groups be present (no optional groups).

提交回复
热议问题