6

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

David Washington
  • 89
  • 1
  • 1
  • 4
  • Also, you are not currently closing the file when you are done with it. You need to do `f.close()` at the end or open the file using a [with-statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) to have it be automatically closed. –  Feb 06 '15 at 23:33

5 Answers5

9

Try a list comprehension which allows you to effectively and efficiently reassign the list to an equivalent list with quotes removed.

g1 = [i.replace('"', '') for i in g1] # remove quote from each element
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
5

You can easily strip off the quote characters using a list comprehension and str.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']
>>>
3

if the list contains only numbers in quotes then cast every element like this:

foo = [int(i) for i in my_list] # cast every element in the list

ORIGINAK:

['1','4','9']

AFTER:

[1,4,9]
minasg
  • 69
  • 3
1

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. 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:
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:
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.

John Y
  • 14,123
  • 2
  • 48
  • 72
0

Maybe we should go back to the source.

Apparently your file contains the text "ELDEN", "DORSEY", "DARELL", "BRODERICK", "ALONSO" (etc). We can delegate the parsing:

import ast

with open("animals.txt") as inf:
    g1 = ast.literal_eval("[" + inf.read() + "]")
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99