Home > Enterprise >  Loop dependent on current (index 1)
Loop dependent on current (index 1)

Time:02-19

I currently have a loop that is dependent on the next index. for example:

numbers = ''
cmd = 'CR10,12,2,35'
for i in range (len(cmd)):
    if cmd[i].isdigit:
       numbers = numbers   cmd[j]
       if cmd[i 1] == ','
           numbers = numbers   ' '
    

I want to do this for all indexes except the last index because it will result in an IndexError.

I still want to read want to add the last number to the string so using range(len(cmd)-1) will not do that.

How do I prevent this from happening?

CodePudding user response:

You can use a try/except block for this:

cmd = 'CR10,12,2,3'
for i in range(len(cmd)):
    try:
        if cmd[i 1] == ',':
            print('do stuff...')
    except IndexError:
        pass

CodePudding user response:

As a solution, i instead added a space (' ') after the cmd string = 'CR10,12,2,3 " and then kept the range to len(cmd)-1. This was it would break out of the loop at the end

  • Related