【发布时间】:2022-01-24 02:50:31
【问题描述】:
我在 python 中有这段代码:
lettonum = {
"a":1,
"b":2,
"c":3
}
def tonum(eput):
output = ""
doing = 1
for _ in range(len(eput)):
mys = lettonum[eput[doing]]
output = f"{output}{mys}"
doing = doing + 1
print(output)
while True:
tonum(input("String to be encoded to numbers: "))
基本上,它应该将字母 a、b 和 c 转换为数字 1、2 和 3
我放了
String to be encoded to numbers: abc
但它会抛出此错误
Traceback (most recent call last):
File "main.py", line 19, in <module>
tonum(input("String to be encoded to numbers: "))
File "main.py", line 13, in tonum
mys = lettonum[eput[doing]]
IndexError: string index out of range
怎么了?
【问题讨论】:
-
python 中的索引从零开始,而不是从一开始。不清楚为什么不使用 for 循环中的值。
-
那我需要加一吗?抱歉,我是循环新手