为了使程序起步,我需要取一个字符串并将数字插入特定位置。我已经做到了。我现在需要做的就是获取它,以便程序将对列表中的每个项目(即数字)执行此操作。我使用内联的for循环,并得到了'TypeError:unhashable type:'list'错误。我也想将结果放在列表中。
我已经完成的工作是编写代码,该代码将替换我正在使用的原始字符串中的数字作为概念证明。但是,当我尝试在前面的代码中插入循环时,出现该错误。代码如下:
s = '<button id="qty_plus_cartline_change_1221067058" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>'
new_string = re.sub('\d+', 'new number', s,1)
print(new_string)
那就是概念证明,可以按我想要的方式替换数字。
updated_list = []
new_string = re.sub('\d+', [i for i in list], s,1)
updated_list.append(new_string)
print(updated_list)
上面是我尝试使用的代码,以将字符串替换为现有列表中的所有数字。
因此,我要寻找的是一个新字符串,其中包含列表(列表)中每个项目的新更新编号。以供参考:
list = [1111111111,2222222222,3333333333,4444444444]
这意味着,我正在寻找的是:
['<button id="qty_plus_cartline_change_1111111111" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_2222222222" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_3333333333" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_4444444444" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>']
任何帮助是极大的赞赏!
您应该re.sub
在列表理解内进行调用,而不是相反。另外,不要命名变量,list
因为它会掩盖内置函数list
。lst
在以下示例中,我将其重命名为:
updated_list = [re.sub('\d+', str(i), s, 1) for i in lst]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句