[英]String Index Out of Range when comparing characters
I am simply trying to compare one character in a string to its neighbor, but I keep getting a string index out of range error.我只是想将字符串中的一个字符与其邻居进行比较,但我不断收到字符串索引超出范围错误。 I can't figure this out.
我想不通。
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
if s[letter] <= s[letter+1]:
current += s[letter]
print(current)
Thanks谢谢
The if statement was unnecessary. if 语句是不必要的。 On the last iteration of the loop,
s[letter+1]
was throwing an error because that index of the string didn't exist.在循环的最后一次迭代中,
s[letter+1]
抛出错误,因为该字符串的索引不存在。 At that point, letter
was equal to the length of your string, s
.那时,
letter
等于字符串的长度s
。 letter+1
was one higher than the length, so the index didn't exist. letter+1
比长度高一,所以索引不存在。
There is no need to compare the value of letter
to the length of s
in the if statement because the loop would end before letter
is greater than the length of s
.无需在 if 语句中将
letter
的值与s
的长度进行比较,因为循环将在letter
大于s
的长度之前结束。
Solution:解决方案:
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
current += s[letter]
print(current)
while @sedavidw is completely right pointing out the indexing issue, it is not a very pythonic way of doing such a comparison.虽然@sedavidw 完全正确地指出了索引问题,但它并不是一种非常pythonic 的方式来进行这种比较。 I'd do something like:
我会做类似的事情:
current = ''.join(letter for letter, next_letter in zip(s, s[1:])
if letter <= next_letter)
I think you want to print a letter only if the previous one is less than the current one.我认为只有在前一封信小于当前一封信时,您才想打印一封信。 The index out of bounds occur because the last index points to (l) but index + 1 points to nothing.
索引越界是因为最后一个索引指向 (l) 但 index + 1 没有指向任何内容。
Here is my solution:这是我的解决方案:
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
if letter + 1 < len(s): # this is important to prevent the index out of bounds error
if s[letter] <= s[letter+1]:
current += s[letter]
print(current)
Output: abbbeggak
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.