python – Removing quotation marks from list items

python – Removing quotation marks from list items

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

python – Removing quotation marks from list items

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 youre looking for, but its 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.

Leave a Reply

Your email address will not be published. Required fields are marked *