'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



Solution 1:[1]

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

Solution 2:[2]

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']
>>>

Solution 3:[3]

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.

Solution 4:[4]

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]

Solution 5:[5]

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() + "]")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Malik Brahimi
Solution 2
Solution 3 John Y
Solution 4
Solution 5 Hugh Bothwell