python-3.x - 将字符串中的数字加一
问题描述
我有一个“注释字符串”,如下所示
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
如果可能的话,我只想通过一个小代码更新其余的数字,因为我希望这种情况会发生几次。
解决方案
您可以尝试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 回调函数,该函数将转换为整数、递增,然后再转换回文本以进行替换。
推荐阅读
- java - 在项目中使用 mockito-inline 会引发“Mockito 无法模拟此类”错误
- angular - 无法在 Google Run 上部署 angular-app
- visual-studio-code - --allow-live 用于 shopify 开发的终端命令
- reactjs - TextInput 样式 Props 类型 react native
- node.js - 如何在expressjs中发送第二个结果
- c# - ASP.NET Core MVC- localhost 当前无法处理此请求
- javascript - React - 何时使用钩子,何时使用 HOC
- qt - QClipboard 中的空白图像
- python - Google Cloud Speech 未安装在 Raspberry Pi 3b+ 上
- javascript - 循环调用api时反应原生,“重新渲染太多”