简体   繁体   中英

Python index out of range?_

The function should delete arguments between () and insert them as a single argument in the list. (Test test2) works. At (Test Test2) (Test3 Test4) it shows an error:

if args[i].startswith('('):
IndexError: list index out of range

Here is the function:

def format_args(args):
    start_string = None
    end_string = None
    in_string = False
    o_string = ''
    for i in range(1, len(args)):
        if args[i].startswith('('):
            if not in_string:
                start_string = i
                in_string = True
        if in_string:
            if args[i].endswith(')'):
                o_string += args[i]
                end_string = i

                for r in range(start_string, end_string+1):
                    args.pop(start_string)
                args.insert(start_string, o_string)
                o_string = ''
                in_string = False

            else:
                o_string += args[i] + ' '

    return args


inp = raw_input('args: ')
args = inp.split(' ')
args.insert(0, "test")
print(format_args(args))

I solved the problem with one line:

args_o = "".join(args).split('\"')

depressing that I needed an hour for it ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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