删除字母S后需要在输出中获取4个URL,但只获取最后一个URL



以下4个URL包含字母s,我们需要删除此字母和打印4个URL,但问题是我只得到了最后一个网站,而不是4打印的站点

注:使用的语言为Python

file1 = ['https:/www.google.comn', 'https:/www.yahoo.comn', 'https:/www.stackoverflow.comn', 
'https:/www.pythonhow.comn']
file1_remove_s = []
for line in file1:
file1_remove_s = line.replace('s','',1)
print(file1_remove_s)

您正在将列表对象中的file1_remove_s重新分配给修改后的列表元素。你想用append代替

file1 = ['https:/www.google.comn', 'https:/www.yahoo.comn', 'https:/www.stackoverflow.comn', 
'https:/www.pythonhow.comn']
file1_remove_s = []
for line in file1:
file1_remove_s.append(line.replace('s','',1))
print(file1_remove_s)

使用=运算符只分配dict上的最后一项。这实际上是一个使用列表理解的完美地方,因此您的代码应该看起来像:

file1 = [file1_remove_s.replace('s','',1) for file1_remove_s in file1]

这将自动附加带有删除的"的格式化文本字符串;s">-到一个列表,通过将该列表的变量名设置为初始列表的名称,初始列表将被具有所需文本的正确格式的新列表覆盖。

最新更新