python 将字母转换为电话号码

python convert letter to telephone number

我是 python 编程的初学者,这是我上 programming.I 的第一个学期,遇到了一些小麻烦。我们正在处理字符串,所以我猜我必须将所有内容都转换为 string.So 这个问题的目标是使用以下单词转换电话号码: 1-800-花到1-800-3569377 我不允许使用列表或字典,只能使用变量并且必须包含一个 WHILE 循环。这是我到目前为止所拥有的:

print('format: X-XXX-XXXXXXX')

user_input = str(input("give me a phone number: "))

key_alph='abcdefghijklmnopqrstuvwxyz'

key_num= '22233344455566677778889999'

total=''

while user_input[6:12].isalpha():

    if user_input[6:12] in key_alph:

        print(user_input[:6]  ,key_num)

如有任何帮助,我们将不胜感激。 可以的话,能不能不说出来呢,不过如果为了说明的缘故必须要说的话就好了。我不知道我是否需要使用索引函数或 .append 方法.... 先感谢您 丹尼米

user_input = (input("give me a phone number: "))

key_alph='abcdefghijklmnopqrstuvwxyz'

key_num= '22233344455566677778889999'

counter = len(user_input[:6])

total=user_input[:6]    #Stores the part of string which is not going to be changed ("1-800-")

while (counter>0):
    alpha = user_input[-counter]
    if alpha.isalpha():   #checks if each character in the input is a valid alphabet and not a number.
        total+=key_num[key_alph.index(alpha)]  #Appending the new characters after the "1-800-" 
    else:
        total+=alpha     #This will preserve if any numeric character is encountered and keeps it same as in the input
    counter -= 1
print total