2017-04-25 53 views
0

后出现的引号所以基本上我工作的文件/ IO实践与一些有心计的字典,每当我有我的返回值的元组里面的字符串在我的字典条目有额外的引号,即使我使用.replace。它得到中间一点都不奇怪,因为文件中有一堆口袋妖怪和“统计”用逗号分隔,有时名字有一个逗号,所以我做它通过名单有多长,以逗号(Python)的奇怪额外甚至更换

拆分后操作

enter image description here

def read_info_file(filename): 
d={} 
with open(filename,'r') as f: 
    next(f) 
    for line in f: 
     h=line.split(',') 
     if len(h)==7: 
      h[1]=str(h[1]+','+h[2]) 
      h[2]=h[3] 
      h[3]=h[4] 
      h[4]=int(h[5]) 
      h[5]=h[6] 

      h[1].replace("\"","") 
      h[2].replace("\"","") 
      h[3].replace("\"","") 
      h[5].replace("\"","") 
      #if there are more than 5 items due to a naming convention 
      #concatanate the name parts and reorder the list properly 
     d[h[1]]=int(h[0]),h[2],h[3],int(h[4]),h[5] 
     #final assignment 
return d 
+0

无论出于何种原因,我的cmd照片没有在http://i.imgur.com/Z77kN49.png –

+0

我不确定你在问什么。你的意思是'Bulbasaur'附近的单引号?这只是为了表明它是一个字符串。 – nico

+0

它看起来像你解析CSV。使用[csv'模块](https://docs.python.org/3/library/csv.html),它将处理引用的字段。不要浪费时间严重重复CSV解析。 – ShadowRanger

回答

0

的Python str是不可变的; str.replace返回一个新的字符串,它不会更改现有的字符串。替换,然后扔掉结果。

您需要指定要剥离的报价结果,例如,更换:

h[1].replace("\"","") # Does replace and throws away result 

有:

h[1] = h[1].replace("\"","") # Does replace and replaces original object with new object 

注意:如果你只是想剥离前和后的报价,我会建议h[1] = h[1].strip('"')这是专门为从两端删除字符(不检查中间)。