Replace part of a string in python multiple times but each replace increments a number in the string by 1

前端 未结 1 829
臣服心动
臣服心动 2021-01-28 04:01

I am modifying html tags in a large html file by giving each tag a unique name with different numbers. So that a javascript function can reference those tags with the modified n

相关标签:
1条回答
  • 2021-01-28 04:11

    If you use re.sub() to do the replacing, you can pass a function as the second argument rather than a plain string. The function will receive a match object based on what the regex matched. You can then use some thinking like itertools.count() (or your own object) to produce increasing numbers.

    For example:

    import re
    from itertools import count
    
    button_number_count = 1;
    htmlString = "this is sometext with more sometext and yet another sometext"
    
    counter = count(button_number_count)
    
    // replace sometext with sometext1, sometext2...
    new_string = re.sub(r'sometext', lambda x: x.group(0) + str(next(counter)), htmlString )
    

    The new_string will look like:

    'this is sometext1 with more sometext2 and yet another sometext3'
    
    0 讨论(0)
提交回复
热议问题