Look ahead in a for loop iterating through a string?

Viewed 5604

I have a simple for loop iterating through a user input string. If the it encounters a certain value, I want to be able to look ahead at the next value in order to determine what to do next. What is the best way to accomplish this? For example in my code below, if it encounters a "1" in the string, it should look at the next character in the string. If it is also a 1, print 1. Otherwise do nothing.

UserInput = input("Enter calculator expression:")

for x in UserInput:
    ...
    ...
    if x == 1:
#       if the next value in the string is 1:
#           print 1
#       else:
#       do nothing
7 Answers

Use range and len in the loop to get position address

UserInput = input("Enter calculator expression")

for i in range(len(UserInput)-1):
    if x[i]=='1':
        if x[i+1]=='1':
            print "something"
        else:
             pass

You can zip a string with itself, but offset with a slice.

>>> from itertools import zip_longest
>>> the_input = 'foobar'  # example
>>> the_input[1:]  # slice off the first character
'oobar'
>>> for c, lookahead in zip_longest(the_input, the_input[1:]):
...   print(c, lookahead)
...
f o
o o
o b
b a
a r
r None

This is more Pythonic than using an index like you would in a language like C. Zipping pairs things elementwise, like the teeth of a zipper.

You can user enumerate() function. something like this,

#!/user/bin/python3
for i,x in enumerate(UserInput):
    if x=='1':
        if UserInput[i+1] == '1':
            print('1')

Firstly, python convention is snake-case (user_input instead)

code below is my solution

from itertools import islice

def window(seq, n=2):
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

pair = list(window(user_input))
comparison_list = ["1"]
result = [x for x,y in pair if x in comparison_list and x == y]

You don't need to look ahead. At least it is not what we usually do when we tackle this kind of problem. Instead, you should look backward - by storing the information. The following example stores the information in a variable state and you can decide the next action in the subsequent iteration.

UserInput = input("Enter calculator expression:")

state = '0'
for x in UserInput:
    if x == '1':
        if state == '1':
            print('1')
        else:
            state = '1'
    else:
        state = '0'

A different (probably more pythonic) way of doing this with the zip function:

for char, next_char in zip(UserInput, UserInput[1:]):
    if char == "1" and char == next_char:
        print(1)
prev_char = None
for char in input("Enter calculator expression:"):
    pass  # Here you can check the current character and the previous character
    if 1 == prev_char and 1 == char:
        print(1)
    prev_char = char
Related