How to apply a function on a backreference?

前端 未结 1 1775
别那么骄傲
别那么骄傲 2021-01-06 04:17

Say I have strings like the following:

old_string = \"I love the number 3 so much\"

I would like to spot the integer numbers (in the exampl

相关标签:
1条回答
  • 2021-01-06 04:34

    In addition to having a replace string, re.sub allows you to use a function to do the replacements:

    >>> import re
    >>> old_string = "I love the number 3 so much"
    >>> def f(match):
    ...     return str(int(match.group(1)) + 1)
    ...
    >>> re.sub('([0-9])+', f, old_string)
    'I love the number 4 so much'
    >>>
    

    From the docs:

    re.sub(pattern, repl, string, count=0, flags=0)

    If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

    0 讨论(0)
提交回复
热议问题