2016-12-24 78 views
0

我有這個字符串:的Python - IndexError:列表索引超出範圍 - For循環/ While循環

string="R$ 35.0123. " 

我要清理的是,採取這一最後的點,並在最後的是空間。使它看起來像這樣:

string:"R$ 35.0123" 

我試圖用這個:

while string[-1].isdigit()==False: 
     string=string[:-1] 

但是我得到這個錯誤:

IndexError: list index out of range 

奇怪的是,我m在for循環中運行,如果循環列表只有一個項目,它可以正常工作。如果列表中有兩個項目,則會發生此問題。

任何想法? 快樂聖誕爲你所有。

FULL下面的代碼 (該字符串變量 「勇敢」)

if CNPJ in page: 
    CNPJloc=[] 
    for i in (re.finditer(CNPJ,page)): 
     CNPJloc.append(i.start()) 

    for i in CNPJloc: 
     CNPJposition=i 
     beg_string=["aviao"] 
     end_string="sicon" 
     for i in beg_string: 
      if i in lower_page[CNPJposition-200:]: 
       beg_string=i     
       extrato_de_contrato=page[lower_page.rfind(beg_string,0,CNPJposition):lower_page.find(end_string,CNPJposition)] 
       lower_extrato=extrato_de_contrato.lower() 
       def valor(): 
        valor=["valor do contrato:","valor:"] 
        for i in valor: 
         if i in lower_extrato: 
          valor=extrato_de_contrato[lower_extrato.rfind(i)+len(i):lower_extrato.find("fonte",lower_extrato.rfind(i))] 
         while valor[-1].isdigit()==False: 
          valor=valor[:-1] 
        print("Valor Total: ", valor) 
        return valor 
       valor() 

回答

0

Python有內置的功能與rstrip

string.rstrip('. ') 

輸出要做到這一點

'R$ 35.0123' 

聽起來就像你只需要刪除最後一個點和之後的所有內容。使用正則表達式

import re 
re.sub('(\.[^.]*)$', '', string) 
+0

尼斯,感謝。問題是有時可能是「。」,其他時間可能只是「。」。其他時間可以是「.xzxzx」。 – abutremutante

+0

另請參見[''str.rsplit' **](https://docs.python.org/2/library/stdtypes.html#str.rsplit)'sep ='。''和'maxsplit = 1 ' –

0

您可能遇到不遵循您的格式並且不包含數字的字符串。

嘗試通過增加len(x) > 0指標確保您的循環:

while len(string) > 0 and not string[-1].isdigit(): 
    del string[-1] 

如果你只是想提取您字符串整數,我建議正則表達式:

import re 
matches = re.findall('\d+\.?\d*', string) 
string = int(matches[0]) if len(matches) > 0 else 0 
0

我發現問題...良好的舊縮進錯誤:

而不是:

  def valor(): 
       valor=["valor do contrato:","valor:"] 
       for i in valor: 
        if i in lower_extrato: 
         valor=extrato_de_contrato[lower_extrato.rfind(i)+len(i):lower_extrato.find("fonte",lower_extrato.rfind(i))] 
        while valor[-1].isdigit()==False: 
         valor=valor[:-1] 

它應該像:

  def valor(): 
       valor=["valor do contrato:","valor:"] 
       for i in valor: 
        if i in lower_extrato: 
         valor=extrato_de_contrato[lower_extrato.rfind(i)+len(i):lower_extrato.find("fonte",lower_extrato.rfind(i))] 
        --> while valor[-1].isdigit()==False: 
        -->  valor=valor[:-1]