将字符串中的数字增加一



我有一个'注释字符串',如下

an_str = r""" Excel file name: {0}
No.of Iterations: {1}
Cp = {2}
CpK = {3}
There are {4}ppm values below the lower tolerance limit
There are {5}ppm values above the upper tolerance limit
""".format(filename, iterations, cp, cpk, ppm_bl, ppm_ol)

随着脚本的发展,新的变量被添加到这个字符串中。新变量总是添加在字符串的开头。因此,当添加一个新变量时,我想将字符串中所有现有的数字都增加1(如下所示(。我可以手动完成,但我想知道regex是否可以用于自动递增。

an_str = r""" Project: {0}
Excel file name: {1}
No.of Iterations: {2}
Cp = {3}
CpK = {4}
There are {5}ppm values below the lower tolerance limit
There are {6}ppm values above the upper tolerance limit
""".format(project,filename, iterations, cp, cpk, ppm_bl, ppm_ol)

我将添加测试Project: {0}&手动project。如果可能的话,我只想通过一个小代码更新其余的数字,因为我预计这种情况会发生好几次。

您可以尝试在这里使用带有回调函数的re.sub

an_str = r"""Excel file name: {0}
No.of Iterations: {1}
Cp = {2}
CpK = {3}
There are {4}ppm values below the lower tolerance limit
There are {5}ppm values above the upper tolerance limit
"""
an_str_out = re.sub(r'{(d+)}', lambda m: '{' + str(int(m.group(1)) + 1) + '}', an_str)
print(an_str_out)

此打印:

Excel file name: {1}
No.of Iterations: {2}
Cp = {3}
CpK = {4}
There are {5}ppm values below the lower tolerance limit
There are {6}ppm values above the upper tolerance limit

这里的想法是使用模式{(d+)}来匹配{num}的每次出现,该模式捕获第一捕获组中的数字。然后,我们将此匹配传递给lambda回调函数,该函数强制转换为integer,递增,然后再强制转换回文本以进行替换。

最新更新