从列表项中删除引号

时间:2015-02-06 23:22:51

标签: python list

我正在运行这个程序:

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

我想要这个出来:

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

相反,我得到了这个:

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

有谁知道如何删除内部引号

4 个答案:

答案 0 :(得分:3)

您可以使用list comprehensionstr.strip

轻松剥离引号字符
f = open( "animals.txt", "r")
g = f.read()
g1 = [x.strip('"') for x in g.split(',')]
print g1

演示:

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

答案 1 :(得分:1)

尝试列表推导,它允许您有效地将列表重新分配到删除了引号的等效列表。

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

答案 2 :(得分:1)

首先创建文件的是什么?看起来你有一种CSV,其中所有元素或至少所有字符串元素都被引号括起来。因此,您至少有两个选择来移动引号删除"上游"从这里的大多数其他答案建议:

  1. 使用csv module
  2. import csv
    with open('animals.txt', 'r') as f:
        g = csv.reader(f)
        g1 = g.next()
    
    1. split()中加入引号,并首先删除引号和尾随引号:
    2. with open('animals.txt', 'r') as f:
          g = f.read()
          g1 = g[1:-1].split('","')
      

      第一种选择可能更多"重量级"比你正在寻找的东西,但它更强大(仍然 重)。请注意,第二个选项假定您的文件末尾没有尾随换行符。如果是,则必须相应调整。

答案 3 :(得分:0)

也许我们应该回到源头。

显然,您的文件包含文字"ELDEN", "DORSEY", "DARELL", "BRODERICK", "ALONSO"(等)。我们可以委派解析:

import ast

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