基本上,该函数返回一个新字符串,该字符串具有电话号码,其中任何字母字符出现在原始文件中,并转换为其等效数字。格式:XXX-XXX-XXXX。
这是我的功能代码:
def translate_phone(xxx):
phonenumber = ''
for alpha in xxx:
if alpha =='A' or alpha =='B' or alpha == 'C' :
phonenumber.append('2')
elif alpha == 'D' or alpha == 'E' or alpha =='F':
phonenumber.append('3')
elif alpha == 'G' or alpha =='H' or alpha =='I':
phonenumber.append('4')
elif alpha == 'J' or alpha =='K' or alpha =='L':
phonenumber.append('5')
elif alpha == 'M' or alpha == 'N' or alpha =='O':
phonenumber.append('6')
elif alpha == 'P' or alpha =='Q' or alpha =='R' or alpha =='S':
phonenumber.append('7')
elif alpha == 'T' or alpha =='U' or alpha =='V':
phonenumber.append('8')
elif alpha == 'W' or alpha =='X' or alpha == 'Y' or alpha =='Z':
phonenumber.append('9')
phonenumber = phonenumber + alpha
print(phonenumber)
这是我在另一个模块中的主要代码:
from _functions import translate_phone
xxx = input('Enter the Number in the following format XXX-XXX-XXXX: ')
xxx = xxx.split('-')
translate_phone(xxx)
错误?每次我运行它都会得到相同的输入。
Enter the Number in the following format XXX-XXX-XXXX: ABC-123-QWER
ABC123QWER
如果有人能暗示我做错了什么或者只是纠正我的错误,我将不胜感激。
答案 0 :(得分:0)
您需要删除代码xxx = xxx.split('-')
并替换您的函数:
def translate_phone(xxx):
phonenumber = list()
for alpha in xxx:
if alpha in ('A', 'B', 'C'):
phonenumber.append('2')
elif alpha in ('D', 'E', 'F'):
phonenumber.append('3')
elif alpha in ('G', 'H', 'I'):
phonenumber.append('4')
elif alpha in ('J', 'K', 'L'):
phonenumber.append('5')
elif alpha in ('M', 'N', 'O'):
phonenumber.append('6')
elif alpha in ('P', 'Q', 'R', 'S'):
phonenumber.append('7')
elif alpha in ('T', 'U', 'V'):
phonenumber.append('8')
elif alpha in ('W', 'X', 'Y', 'Z'):
phonenumber.append('9')
else:
phonenumber.append(alpha)
return ''.join(phonenumber)
或
def translate_phone(xxx):
phonenumber = list()
for alpha in xxx:
phonenumber.append(\
'2' if alpha in ('A', 'B', 'C') else \
'3' if alpha in ('D', 'E', 'F') else \
'4' if alpha in ('G', 'H', 'I') else \
'5' if alpha in ('J', 'K', 'L') else \
'6' if alpha in ('M', 'N', 'O') else \
'7' if alpha in ('P', 'Q', 'R', 'S') else \
'8' if alpha in ('T', 'U', 'V') else \
'9' if alpha in ('W', 'X', 'Y', 'Z') else alpha)
return ''.join(phonenumber)