2017-04-25 172 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('"')這是專門爲從兩端刪除字符(不檢查中間)。