Python 未返回正确的打印语句
基本上,该函数返回一个新字符串,该字符串包含电话号码和原始字符串中出现的任何字母字符,并将其转换为等效的数字。格式:XXX-XXX-XXXX 这是我的功能代码:Python 未返回正确的打印语句,python,python-3.x,Python,Python 3.x,基本上,该函数返回一个新字符串,该字符串包含电话号码和原始字符串中出现的任何字母字符,并将其转换为等效的数字。格式: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' o
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
如果有人能提示我做错了什么或只是简单地纠正我的错误,我们将不胜感激。您需要删除代码
xxx=xxx。拆分('-')
,并为此替换您的函数:
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)
或
xxx.split('-')
从不返回A
或任何其他字母。这就是为什么你从不在if语句中输入。然后字符串没有append方法…好的,我已经这样做了,基本上我的phonenumber=[],这是我现在的示例输出:按以下格式输入数字XXX-XXX-XXXX:ALC-LOL-123[2,5,2,5,6,5]
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)