'Loop dependent on current (index + 1)
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?
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dissenter |
| Solution 2 | Zaid Fanek |
