代码之家  ›  专栏  ›  技术社区  ›  krock1516

元组索引超出打印索引值的范围

  •  0
  • krock1516  · 技术社区  · 8 年前

    在执行下面的代码时,我得到了下面的错误,仅供参考 matchObj 这里返回一个元组值..

    $ ./ftpParser3_re_dup.py
    Traceback (most recent call last):
      File "./ftpParser3_re_dup.py", line 13, in <module>
        print("{0:<30}{1:<20}{2:<50}{3:<15}".format("FTP ACCOUNT","Account Type","Term Flag"))
    IndexError: tuple index out of range
    

    代码如下:

    from __future__ import print_function
    from signal import signal, SIGPIPE, SIG_DFL
    signal(SIGPIPE,SIG_DFL)
    import re
    with open('all_adta', 'r') as f:
        for line in f:
            line = line.strip()
            data = f.read()
            # Making description & termflag optional in the regex pattern as it's missing in the "data_test" file with several occurrences.
            regex = (r"dn:(.*?)\nftpuser: (.*)\n(?:description:* (.*))?\n(?:termflag:* (.*))")
            matchObj = re.findall(regex, data)
            print("{0:<30}{1:<20}{2:<50}{3:<15}".format("FTP ACCOUNT","Account Type","Term Flag"))
            print("{0:<30}{1:<20}{2:<50}{3:<15}".format("-----------","------------","--------"))
            for index in matchObj:
                index_str = ' '.join(index)
                new_str = re.sub(r'[=,]', ' ', index_str)
                new_str = new_str.split()
                # In below print statement we are using "index[2]" as index is tuple here, this is because
                # findall() returns the matches as a list, However with groups, it returns it as a list of tuples.
                print("{0:<30}{1:<20}{2:<50}{3:<15}".format(new_str[1],new_str[8],index[2],index[3]))
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   unholy_me    8 年前

    排队 print("{0:<30}{1:<20}{2:<50}{3:<15}".format("FTP ACCOUNT","Account Type","Term Flag")) 你提到了4个指数,但只有3个。 "FTP ACCOUNT","Account Type","Term Flag" 删除第四个索引或添加新索引

    推荐文章