I have the first two strings in a string list strs that is guaranteed to have length of at least 2. I want to compare their letters against each other, and perform a task when their letters are identical. Here is the code I am using:
iter_len = len(strs[1])
if (len(strs[0]) >= len(strs[1])):
iter_len = len(strs[0])
for i in range (0, iter_len, 1):
if (strs[0][i] == strs[1][i]):
[do a thing]
However, when I run this, I get a IndexError: string index out of range for the if (strs[0][i] == strs[1][i]): line. I don’t quite understand why this is happening, as the first if statement should ensure that iter_len is the minimum length between strs[0] and strs[1], and should prevent the index from going over. Any advice is much appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you need to iterate through two sequences in lockstep, it’s generally best practice to use zip:
for a,b in zip(strs[0], strs[1]):
if a == b:
#[do a thing]
This will deal with the issue of one sequence being longer than the other.
If you need the index, you can use enumerate with your zip:
for i, (a, b) in enumerate(zip(strs[0], strs[1])):
if a == b:
#[do a thing with i]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0