我当前正在编写一个函数,该函数接受一个字符串并将该字符串(即电话号码)仅转换为数字。另外,我还使用while循环询问用户是否要继续。我的输出仅显示我输入的第一个数字或字母,我想知道为什么。这是我到目前为止的内容:
def translate_num(convert):
answer=input('insert y to continue')
convert=input('Enter phone number here')
while answer=='y':
for word in convert:
phone_num=[]
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
print(phone_num)
answer=input('insert y to continue')
return
translate_num('555-361-FOOD')
答案 0 :(得分:0)
您正在遍历phone_num
中的每个值之后,用phone_num=[]
值重新初始化convert
。而是在函数开始时一次声明phone_num=[]
,也正如kabanus指出的那样,return语句需要由一个块取消。我的以下实现似乎可行(由于您已经在调用函数,因此我删除了多余的输入语句,还添加了将数字列表转换回字符串的代码:
def translate_num(convert):
#answer=input('insert y to continue')
#convert=input('Enter phone number here')
phone_num=[]
while True:
for word in convert:
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
#print(phone_num)
#answer=input('insert y to continue')
number=''
for item in phone_num:
number=number+str(item)
return (number)
print (translate_num('555-361-FOOD'))