如何修复 Python 中超出范围的字符串索引
How To Fix String Index Out of Range in Python
我目前正在学习 python。书中有一个练习概述了解码代码。我遵循了这段代码,但是我一直在程序中间返回错误。
这是导致问题的代码:
def decode(string_for_decoding):
result = ""
for i in range(0, len(string_for_decoding)):
if string_for_decoding[i+1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i+1])
elif string_for_decoding[i].isalpha():
result += string_for_decoding[i]
return result
string_for_decoding = input("Enter a string to decode: ")
print(decode(string_for_decoding))
您正在尝试获取不能等于或大于 len(string)
的索引 i+1
。
您正从 0 to len(string)
进入 for
循环,您正试图访问索引:i+1
这是根本原因!或者:
- 迭代直到减少一个长度,例如直到
len(string) - 1
- 或者使用索引
里面适当
此外,强烈建议不要使用 range(len(x))
。您可以简单地遍历任何集合数据类型 for i in x:
如果您也想要索引,请查看 enumerate()
。而且您可以完全忘记索引错误。
检查范围内的索引是否大于字符串中的字符数。它可能看起来像这样:
def decode(string_for_decoding: str):
result = ""
for i in range(0, len(string_for_decoding)):
if len(string_for_decoding) > i + 1 and string_for_decoding[i + 1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i + 1])
elif string_for_decoding.isalpha():
result += string_for_decoding[i]
return result
print(decode(input("Enter a string to decode: ")))
我目前正在学习 python。书中有一个练习概述了解码代码。我遵循了这段代码,但是我一直在程序中间返回错误。
这是导致问题的代码:
def decode(string_for_decoding):
result = ""
for i in range(0, len(string_for_decoding)):
if string_for_decoding[i+1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i+1])
elif string_for_decoding[i].isalpha():
result += string_for_decoding[i]
return result
string_for_decoding = input("Enter a string to decode: ")
print(decode(string_for_decoding))
您正在尝试获取不能等于或大于 len(string)
的索引 i+1
。
您正从 0 to len(string)
进入 for
循环,您正试图访问索引:i+1
这是根本原因!或者:
- 迭代直到减少一个长度,例如直到
len(string) - 1
- 或者使用索引 里面适当
此外,强烈建议不要使用 range(len(x))
。您可以简单地遍历任何集合数据类型 for i in x:
如果您也想要索引,请查看 enumerate()
。而且您可以完全忘记索引错误。
检查范围内的索引是否大于字符串中的字符数。它可能看起来像这样:
def decode(string_for_decoding: str):
result = ""
for i in range(0, len(string_for_decoding)):
if len(string_for_decoding) > i + 1 and string_for_decoding[i + 1].isdigit():
result += string_for_decoding[i] * int(string_for_decoding[i + 1])
elif string_for_decoding.isalpha():
result += string_for_decoding[i]
return result
print(decode(input("Enter a string to decode: ")))