我有一个字符串列表,但有两组标点符号:
list_A = ['',
" 'train set'",
" 'toy train set'",
" 'train track'",]
我试图删除每个字符串上多余的双引号,不想删除单个引号,以防它是撇号。
我试过:
new_list = []
for i in list_A:
i = i.strip('"')
new_list.append(i)
print(i)
但是当我打印new_list时,标点符号仍然没有消失,当我打印列表的第二个元素(问题的关键(时,它们仍然存在
new_list
['',
" 'train set'",
" 'toy train set'",
" 'train track'"]
new_list[1]
" 'train set'"
不要忘记,不能为变量使用名称"list"。
我给你下一个代码:
list1 = ['', " 'train set'", " 'toy train set'", " 'train track'"]
new_list = [i.replace("'", '') for i in list1]
使用.replace()
listt = ['',
" 'train set'",
" 'toy train set'",
" 'train track'",]
newlist = []
for i in listt:
new = i.replace("'","")
newlist.append(new)
print(newlist)
另一种实现列表理解的方法,
newlist = [i.replace("'","") for i in list]