我的代码可以将手机信件转换为电话号码,但我不知道是否有更好的方法可以做到这一点:
def phone_letter_converter(self):
if not self.isdigit():
number_upper = self.upper()
new_number = ""
for ch in number_upper:
if ch == 'A' or ch == 'B' or ch == 'C':
new_number += '2'
elif ch == 'D' or ch == 'E' or ch == 'F':
new_number += '3'
elif ch == 'G' or ch == 'H' or ch == 'I':
new_number += '4'
elif ch == 'J' or ch == 'K' or ch == 'L':
new_number += '5'
elif ch == 'M' or ch == 'N' or ch == 'O':
new_number += '6'
elif ch == 'P' or ch == 'Q' or ch == 'R' or ch == 'S':
new_number += '7'
elif ch == 'T' or ch == 'U' or ch == 'V':
new_number += '8'
elif ch == 'W' or ch == 'X' or ch == 'Y' or ch == 'Z':
new_number += '9'
else:
new_number += ch
return new_number
答案 0 :(得分:1)
您可以使用in
运算符:
因此,if ch == 'A' or ch == 'B' or ch == 'C':
代替if ch in 'ABC'
,会检查(例如)A
是否在ABC
。
或者,你可以在这里使用dictionary:
conversion_dict = {'A': '2', 'B': '2', 'C': '2',\
'D': '3', 'E': '3', 'F': '3',\
'G': '4', 'H': '4', 'I': '4',\
'J': '5', 'K': '5', 'L': '5',\
'M': '6', 'N': '6', 'O': '6',\
'P': '7', 'Q': '7', 'R': '7', 'S': '7',\
'T': '8', 'U': '9', 'V': '8',\
'W': '9', 'X': '9', 'Y': '9', 'Z': '9'}
number_letters = 'KJLWABJEKF'
new_number = ""
for c in number_letters:
new_number += conversion_dict[c]
print(new_number) # 5559225353
使用"".join(...)
和list comprehension可以进一步缩短这一点:
number_letters = 'KJLWABJEKF'
new_number = ''.join([conversion_dict[c] for c in number_letters]) # 5559225353
答案 1 :(得分:0)
您可以使用dict进行映射,例如:
letter_to_number = dict(
A=2, B=2, C=2, D=3, E=3, F=3,
G=4, H=4, I=4, J=5, K=5, L=5,
M=6, N=6, O=6, P=7, Q=7, R=7, S=7,
T=8, U=8, V=9, W=9, X=9, Y=9, Z=9,
)
letter_to_number = {k: str(v) for k, v in letter_to_number.items()}
letter_to_number.update({k.lower(): v for k, v in letter_to_number.items()})
def phone_letter_converter(letters_in):
return ''.join(letter_to_number.get(l, l) for l in letters_in)
这是通过为数字构建大写字母的初始字典来实现的。然后将数字转换为这些数字的字母,然后添加查找的小写版本。
print(phone_letter_converter('AbCdZ'))
22239