Reputation: 1081
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
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
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
Reputation: 114038
what you probably want is
for i in range(len(str)-1):
if str[i] <= str[i+1]:
Upvotes: 1