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

1

5 Answers

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

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

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.

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]

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest