首页 > 解决方案 > 如何每次用给定列表的新字符替换字符串中的字符 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 循环的不同方法,但并没有完全掌握它。你们能帮帮我吗?

标签: pythonfor-loopreplaceformat

解决方案


你应该使用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

推荐阅读