python - 如何每次用给定列表的新字符替换字符串中的字符 n 次?
问题描述
我有以下字符串,我想A1
用列表的每个字符替换befcodes
并打印它:
befcodes = ["A1","A2","A3","A4","A5","A6","A7","A8","A9","10","11","12","13","14","15","16","17","18","19","20"]
telegram = "$00;02;A1;00000000*49"
我想得到一个看起来像这样的输出:
$00;02;A1;00000000*49
$00;02;A2;00000000*49
$00;02;A3;00000000*49
......
$00;02;19;00000000*49
$00;02;20;00000000*49
我尝试了几种使用字符串格式化和 for 循环的不同方法,但并没有完全掌握它。你们能帮帮我吗?
解决方案
你应该使用str.replace
befcodes = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]
telegram = "$00;02;A1;00000000*49"
for code in befcodes:
print(telegram.replace("A1", code))
给予
$00;02;A1;00000000*49
$00;02;A2;00000000*49
$00;02;A3;00000000*49
...
$00;02;18;00000000*49
$00;02;19;00000000*49
$00;02;20;00000000*49
推荐阅读
- string - VHDL - 将字符串转换为 32 位整数
- python - 从列表中删除可被 5 整除的数字的 Python 程序返回错误值
- scheme - 呼叫 cc 示例球拍
- c - 如何在 vs 代码中优先考虑用户片段而不是扩展片段?
- android - BroadcastReceiver(已注册清单)生命周期
- c++ - 哪种排序算法最适合这个特性?
- sql-server - 如何将 SQL Server CTE 查询转换为普通查询
- android - 应用程序运行时调试器未连接
- c# - C# - 将数据从十进制转换为浮点数在从数据库中检索数据时截断小数点后
- react-native - 如何在 createMaterialTopTabNavigator 选项卡中设置两种颜色