简体   繁体   English

Python-IndexError:列表索引超出范围-For循环/ While循环

[英]Python - IndexError: list index out of range - For loop / While loop

I have this string: 我有这个字符串:

string="R$ 35.0123. "

I want to clean that, taking that final dot and that space in the end out. 我要清理掉最后一个点和最后一个空格。 Making it look like this: 使它看起来像这样:

string:"R$ 35.0123"

I'm trying to use this: 我正在尝试使用此:

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

However I'm getting this error: 但是我收到此错误:

IndexError: list index out of range

The weird thing is that I'm running this inside a for loop and if the looped list has only one item, it works fine. 奇怪的是,我在for循环中运行此程序,如果循环列表中只有一项,则可以正常工作。 If the list has two items, this problem happens. 如果列表中有两个项目,则会出现此问题。

Any ideas? 有任何想法吗? Merry xmas for you all. 祝大家圣诞快乐。

FULL CODE BELOW (the string is the variable "valor") 下方完整代码 (字符串为变量“ valor”)

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()

Python has functionality built in to do this with rstrip Python内置了使用rstrip做到这一点的rstrip

string.rstrip('. ')

Output 产量

'R$ 35.0123'

Sounds like you just need to remove the last dot and everything after that. 听起来您只需要删除最后一个圆点及其后的所有内容即可。 Use regex 使用正则表达式

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

You are probably encountering a string that doesn't follow your format, and contain no digits. 您可能遇到的字符串不符合您的格式,并且不包含数字。

Try securing your loop by adding a len(x) > 0 indicator: 尝试通过添加len(x) > 0指示器来保护循环:

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

If you just want to extract the integer from you string, I would suggest regex: 如果只想从字符串中提取整数,我建议使用正则表达式:

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

I found the problem... the good old indentation error: 我发现了问题...好的旧缩进错误:

Instead of: 代替:

            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]

It should go like: 它应该像这样:

            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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM