首页 > 解决方案 > 在 Python 中使用循环替换字符串

问题描述

我还是 Python 的新手,我很难知道如何循环这个。

mynewvar2=varlist3.replace('R0','_0').replace('R1','_1').replace('R2','_2').replace('R3','_3').replace('R4','_4').replace('R5','_5').replace('R6','_6').replace('R7','_7').replace('R8','_8').replace('R9','_9')

这里的问题是,如果我得到的不止这些,我将添加许多 .replace() 函数。

非常感谢你们的帮助!

标签: pythonstringloopsreplace

解决方案


In [1]: s = 'XR0R1R2R3'

In [2]: before = ['R0','R1','R2','R3']

In [3]: after = ['_0','_1','_2','_3']

In [4]: for a, b in zip(before, after):
   ...:     s = s.replace(a, b)
   ...:     

In [5]: s
Out[5]: 'X_0_1_2_3'

推荐阅读