尝试让这个程序将字母翻译成数字,以便可以输入带有单词的电话号码并输出数字版本。 (1800GOTJUNK = 18004685865) 不确定我哪里出错了,但每个输出只给出最后一个字母是什么,并为所有数字重复它的数字 (1800adgjmptw = 18009999999)。非常感谢任何帮助,谢谢。
def transNum(string):
number = 1
for ch in string:
if ch.lower() in "abc":
number = 2
elif ch.lower() in "def":
number = 3
elif ch.lower() in "ghi":
number = 4
elif ch.lower() in "jkl":
number = 5
elif ch.lower() in "mno":
number = 6
elif ch.lower() in "pqrs":
number = 7
elif ch.lower() in "tuv":
number = 8
elif ch.lower() in "wxyz":
number = 9
return number
def translate(phone):
newNum = ""
for ch in phone:
if ch in ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]:
newNum = newNum + str(transNum(phone))
else:
newNum = newNum + ch
return newNum
def main():
phone = input("enter a phone number")
noLetters = translate(phone)
print("The number you entered: ", phone)
print("Translates to: ", noLetters)
main()
str(transNum(phone))
应该是 str(transNum(ch))
而且 transNum 不需要迭代其输入,因为它只会保留最后一个数字(它被设计为将一个字母作为输入)。
我是一名优秀的程序员,十分优秀!