Py学习  »  Python

在python中多次替换字符串的一部分,但每次替换都会使字符串中的数字增加1

yo76yo • 6 年前 • 1906 次点击  

button_number_count = 1;

htmlString = "<img class=\"hiddenCopy\" onclick=\"copyCodeButton("+str(button_number_count)+")\"src=\"../img/Log in.png\"/>";

但是我想在一个更大的字符串上执行替换函数,在这个字符串中,我替换了一个特定的文本字段,在执行此操作时,我会增加这个数字。

content_with_replace = content_with_replace.replace_while_Incr('</pre></code>','</pre></code>'+"<img... %d ...>", button_number_count, number_of_replaces );

%d .

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/35920
文章 [ 1 ]  |  最新文章 6 年前
Mark Meyer
Reply   •   1 楼
Mark Meyer    6 年前

如果你使用 re.sub() match itertools.count()

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 )

'this is sometext1 with more sometext2 and yet another sometext3'