python将字母转换为电话号码



我是python编程的初学者,这是我学习编程的第一个学期。我有点小麻烦。我们正在处理字符串,所以我想我必须将所有内容转换为字符串。因此,这个问题的目标是将电话号码转换为以下单词:1-800-flowers至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)

任何帮助都将不胜感激。如果可能的话,可以不透露答案吗?但如果奥尤必须这样做才能解释,那就好了。我不知道是需要使用index函数还是.append方法。。。。提前谢谢danny m

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

最新更新