尝试使该程序将字母转换为数字,以便可以输入带单词的电话号码并输出数字版本。 (1800GOTJUNK = 18004685865)不知道Im哪里出错了,但是每个输出都给出最后一个字母,然后对所有数字重复其数字(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不需要遍历其输入,因为它只会保留最后一个数字(它被设计为以单个字母作为输入)。