2016-12-24 82 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]