在Python中使用循环替换字符串

2024-04-29 04:35:45 发布

您现在位置: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()函数

非常感谢你们的帮助


Tags: replace经历r2r3r5r8r0r1
1条回答
网友
1楼 · 发布于 2024-04-29 04:35:45
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'

相关问题 更多 >