如何从python列表中的字符串中删除双引号? [英] How to remove double quotes from strings in a list in python?

查看:180
本文介绍了如何从python列表中的字符串中删除双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从词典列表中获取一些数据。
数据来自csv文件,因此都是字符串。
文件中的键都具有双qoutes,但是由于它们都是字符串,因此我想删除它们,使它们在字典中看起来像这样:

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}

而不是这个

{'"key"':value}

我只是尝试使用string = string [1:-1],但这没用...

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

这是我的代码:

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

我从印刷品获得的所有印刷品都不错,没有双引号,但是当我将数据附加到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?

推荐答案

正如注释中所述,在处理CSV文件时,您确实应该使用Python的内置 csv模块(似乎链接到Python 2文档

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)

返回列表中的每个项目,如果不为空,则为字符串。在循环中进行类型检查没有任何意义(尽管如果有原因,您会使用 isinstance )。尽管您可能使用了unicode字符串,但我不知道对此有什么解决办法。在Python 2上,通常可以使用 isinstance(...,basestring),其中 basestring 是两个 str unicode 。在Python 3上,只需使用 str ,除非您知道要处理的是 bytes

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.

这篇关于如何从python列表中的字符串中删除双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆