Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telling Python to stop comparing in a for loop when it gets to the last character

At the moment I have code that is looking through a huge string. It compares the string like this:

a = 0
for letter in my_str:
    a += 1
    if letter <= my_str[a]:

It keeps comparing all the way until the end when I get a 'string index out of range' error. I know it is because it is trying to compare the last character in the string to the next character (which doesn't exist) How to fix this! I feel like I have tried everything. Help appreciated.

EDIT: Seems as though I have just figured out my solution... thanks anyways.

like image 468
user1294377 Avatar asked Jan 25 '26 01:01

user1294377


2 Answers

Using pairwise recipe from itertools

>>> from itertools import tee, izip
>>> def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)

>>> text = 'abc'
>>> for x, y in pairwise(text):
        if x <= y:
            pass
like image 154
jamylak Avatar answered Jan 27 '26 15:01

jamylak


Avoid using indexes to work with strings when iterating over them. Instead of comparing the current letter to the next one, compare the current letter to the previous one, which you have saved from the last pass through the loop. Initialize the "previous" variable outside the loop to something sensible for the first pass.

lastletter = ""
for letter in text:
    if lastletter <= letter:   # always true for first char
        # do something
    lastletter = letter
like image 43
kindall Avatar answered Jan 27 '26 14:01

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!