user1294377
user1294377

Reputation: 1081

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.

Upvotes: 3

Views: 136

Answers (4)

kindall
kindall

Reputation: 184280

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

Upvotes: 2

user1294377
user1294377

Reputation: 1081

I just added another if statement at the beginning like the following..

if a < len(str):

Don't know why it took me so long to figure that out!

Upvotes: -2

Joran Beasley
Joran Beasley

Reputation: 114038

what you probably want is

for i in range(len(str)-1):
    if str[i] <= str[i+1]:

Upvotes: 1

jamylak
jamylak

Reputation: 133634

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

Upvotes: 2

Related Questions