首页 > 解决方案 > 将字符串中的数字加一

问题描述

我有一个“注释字符串”,如下所示

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(如下所示)。我可以手动完成,但我想知道是否可以使用正则表达式自动增加它。

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如果可能的话,我只想通过一个小代码更新其余的数字,因为我希望这种情况会发生几次。

标签: python-3.xregex

解决方案


您可以尝试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

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


推荐阅读