EerlijkeDame
EerlijkeDame

Reputation: 507

How to remove double quotes from strings in a list in python?

I am trying to get some data in a list of dictionaries. The data comes from a csv file so it's all string. the the keys in the file all have double qoutes, but since these are all strings, I want to remove them so they look like this in the dictionary:

{'key':value}

instead of this

{'"key"':value}

I tried simply using string = string[1:-1], but this doesn's work...

Here is my code:

csvDelimiter = ","
tsvDelimiter = "\t"
dataOutput = []

dataFile = open("browser-ww-monthly-201305-201405.csv","r")

for line in dataFile:
    line = line[:-1]    # Removes \n after every line

    data = line.split(csvDelimiter)

    for i in data:
        if type(i) == str:    # Doesn't work, I also tried if isinstance(i, str)
                              # but that didn't work either.
            print i
            i = i[1:-1]
            print i
    dataOutput.append({data[0] : data[1]})

dataFile.close()

print "Data output:\n"
print dataOutput

all the prints I get from print i are good, without double quotes, but when I append data to dataOutput, the quotes are back!

Any idea how to make them disappear forever?

Upvotes: 4

Views: 45701

Answers (3)

msch
msch

Reputation: 1396

You said: "I tried simply using string = string[1:-1], but this doesn't work...". It seems to work fine for me:

In [101]: s="'word'"
In [102]: s[1:-1]
Out[102]: 'word'

Upvotes: 1

Iguananaut
Iguananaut

Reputation: 23306

As noted in the comments, when dealing with CSV files you truly ought to use Python's built-in csv module (linking to Python 2 docs since it seems that's what you're using).

Another thing to note is that when you do:

data = line.split(csvDelimiter)

every item in the returned list, if it is not empty, will be strings. There's no sense in doing a type check in the loop (though if there were a reason to you would use isinstance). I don't know what "didn't work" about it, though it's possible you were using unicode strings. On Python 2 you can usually use isinstance(..., basestring) where basestring is a base class for both str and unicode. On Python 3 just use str unless you know you're dealing with bytes.

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172229

Strip it. For example:

data[0].strip('"')

However, when reading cvs files, the best is to use the built-in cvs module. It takes care of this for you.

Upvotes: 8

Related Questions