简体   繁体   English

删除列表项中的引号

[英]Removing quotation marks from list items

I am running this program: 我正在运行此程序:

f = open( "animals.txt", "r")
g = f.read()
g1 = g.split(',') #turning the file into list
print g1

And I want this to come out: 我希望这个结果出来:

['ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO']

Instead, I am getting this: 相反,我得到这个:

['"ELDEN"', '"DORSEY"', '"DARELL"', '"BRODERICK"', '"ALONSO"']

Does anyone know how to remove the inner quotes 有谁知道如何删除内引号

You can easily strip off the quote characters using a list comprehension and str.strip : 您可以使用列表 str.stripstr.strip轻松删除引号字符:

f = open( "animals.txt", "r")
g = f.read()
g1 = [x.strip('"') for x in g.split(',')]
print g1

Demo: 演示:

>>> lst = ['"ELDEN"', '"DORSEY"', '"DARELL"', '"BRODERICK"', '"ALONSO"']
>>> [x.strip('"') for x in lst]
['ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO']
>>>

尝试使用列表理解,您可以有效地将列表重新分配为删除引号的等效列表。

g1 = [i.replace('"', '') for i in g1] # remove quote from each element

What is creating your file in the first place? 首先是什么创建文件? It looks as though you have a kind of CSV where either all elements, or at least all string elements, are surrounded by quotation marks. 好像您有一种CSV,其中所有元素或至少所有字符串元素都用引号引起来。 As such, you have at least a couple of choices for moving the quotation-mark removal "upstream" from what most of the other answers here are suggesting: 这样,您至少有两个选择可以将引号删除“上游”移到此处建议的其他大多数答案中:

  1. Use the csv module : 使用csv模块
 import csv with open('animals.txt', 'r') as f: g = csv.reader(f) g1 = g.next() 
  1. Include the quotation marks in your split() , and chop off the leading and trailing quotes first: 在您的split()包括引号,并首先将前导和尾引号切掉:
 with open('animals.txt', 'r') as f: g = f.read() g1 = g[1:-1].split('","') 

The first option may be somewhat more "heavyweight" than what you're looking for, but it's more robust (and still not that heavy). 第一种选择可能比您想要的东西更“重”,但是它更可靠(但仍然不那么重)。 Note that the second option assumes that your file does NOT have a trailing newline at the end. 请注意,第二个选项假定您的文件末尾没有换行符。 If it does, you have to adjust accordingly. 如果是这样,则必须进行相应的调整。

Maybe we should go back to the source. 也许我们应该回到源头。

Apparently your file contains the text "ELDEN", "DORSEY", "DARELL", "BRODERICK", "ALONSO" (etc). 显然,您的文件包含文本"ELDEN", "DORSEY", "DARELL", "BRODERICK", "ALONSO" (等)。 We can delegate the parsing: 我们可以委托解析:

import ast

with open("animals.txt") as inf:
    g1 = ast.literal_eval("[" + inf.read() + "]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM