python - 在 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() 函数。
非常感谢你们的帮助!
解决方案
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'
推荐阅读
- objective-c - 在 UITableViewCell 中设置 UISwitch 会触发其他 UISwitch
- python - 如何使用 python 从 https://www.bayut.com/index/sale-prices-2-bed-apartments-al-raha-beach.html 获取图形数据
- testing - TestCafe:具有动态 ID 的 Web 应用程序(XAF 应用程序)
- typescript - TypeScript generics: how to define type T which is structurally the same as other type S
- python - 具有张量流概率的贝叶斯线性回归
- c# - 如何覆盖 HashSet 的 + 运算符
在c#中 - javascript - WordPress awesomplete 没有在提交时将点击的建议查询字符串添加到 URL 的末尾
- javascript - 如何在上下文中的useEffect挂钩中传递依赖关系
- hadoop - Hadoop webapps - 纱线用户界面
- sql - 根据另一个表更改选择中的列名