【问题标题】:Turn letters to number not working python将字母转换为数字不起作用 python
【发布时间】: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 循环中的值。
  • 那我需要加一吗?抱歉,我是循环新手

标签: python string


【解决方案1】:

除非你真的需要索引,否则 Python 不鼓励循环遍历范围。当 python 让您更轻松地直接迭代值时,执行 for index in range(len(something)): 然后 something[index] 是一种浪费。这样做的主要优点之一是您可以避免遇到非常常见的索引问题:

lettonum = {
    "a":1,
    "b":2,
    "c":3
}

def tonum(eput):
    output = ""
    for letter in eput:
        mys = lettonum[letter]
        output += str(mys)
    print(output)


tonum('abc')
# 123

【讨论】:

    【解决方案2】:

    您应该从 0 开始索引,而不是 1:

    lettonum = {
      "a": 1,
      "b": 2,
      "c": 3
    }
    
    
    def tonum(eput):
        global lettonum
        output = ""
        doing = 0
        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: "))
    

    或带有索引的替代(和更好)解决方案:

    def tonum(eput):
        global lettonum
        output = ""
        for doing in range(len(eput)):
            mys = lettonum[eput[doing]]
            output = f"{output}{mys}"
        print(output)
    

    【讨论】:

    • 完美运行!谢谢!
    • 我的荣幸,先生!如果我或任何其他对原始问题的回答有帮助,请随时将其标记为正确。
    【解决方案3】:

    索引从 0 开始,而不是 1。

    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: "))
    

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2011-05-30
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多