将 phone 数字转换为 phone 'word' - python
converting phone number into phone 'word' - python
我想将给定的 phone 数字转换成相应的字母
0 -> 'a'
1 -> 'b'
2 -> 'c' etc.
例如数字 210344222 应转换为字符串 'cbadeeccc'。
我知道我的 return 最后是错误的,这是我被卡住的地方,所以你能解释一下我将如何 return 字母转换。
def phone(x):
"""
>>> phone(22)
'cc'
>>> phone(1403)
'bead'
"""
result = ""
x = str(x)
for ch in x:
if x == 0:
print('a')
elif x == 1:
print('b')
elif x == 3:
print('c')
return result
有一个名为ascii_lowercase
in the string
package的常量可以按照您描述的方式将数字转换为字母,您可以使用数字并在ascii_lowercase
中获取该索引来获取字母
from string import ascii_lowercase
phone_number = "210344222"
converted = ''.join(ascii_lowercase[int(i)] for i in phone_number)
您可以尝试使用内置的 chr()
方法:
def phone(x):
return ''.join((chr(int(i) + 97)) for i in x)
print(phone('210344222'))
输出:
cbadeeccc
其中 chr(97)
returns 'a'
, chr(98)
returns 'b'
, 依此类推,因此 int(i) + 97
位.
使用 chr() 和 ord() 并计算 'a' + 数字
def phone(x):
"""
>>> phone(22)
'cc'
>>> phone(1403)
'bead'
"""
result = ""
x = str(x)
result = result.join([chr(int(ch) + ord('a')) for ch in x])
return result
print(phone('22'))
print(phone('1403'))
def phone(x):
result = []
x = str(x)
for ch in x:
if ch == '0':
result.append('a')
elif ch == '1':
result.append('b')
elif ch == '3':
result.append('c')
return ''.join(result)
我想将给定的 phone 数字转换成相应的字母
0 -> 'a'
1 -> 'b'
2 -> 'c' etc.
例如数字 210344222 应转换为字符串 'cbadeeccc'。 我知道我的 return 最后是错误的,这是我被卡住的地方,所以你能解释一下我将如何 return 字母转换。
def phone(x):
"""
>>> phone(22)
'cc'
>>> phone(1403)
'bead'
"""
result = ""
x = str(x)
for ch in x:
if x == 0:
print('a')
elif x == 1:
print('b')
elif x == 3:
print('c')
return result
有一个名为ascii_lowercase
in the string
package的常量可以按照您描述的方式将数字转换为字母,您可以使用数字并在ascii_lowercase
中获取该索引来获取字母
from string import ascii_lowercase
phone_number = "210344222"
converted = ''.join(ascii_lowercase[int(i)] for i in phone_number)
您可以尝试使用内置的 chr()
方法:
def phone(x):
return ''.join((chr(int(i) + 97)) for i in x)
print(phone('210344222'))
输出:
cbadeeccc
其中 chr(97)
returns 'a'
, chr(98)
returns 'b'
, 依此类推,因此 int(i) + 97
位.
使用 chr() 和 ord() 并计算 'a' + 数字
def phone(x):
"""
>>> phone(22)
'cc'
>>> phone(1403)
'bead'
"""
result = ""
x = str(x)
result = result.join([chr(int(ch) + ord('a')) for ch in x])
return result
print(phone('22'))
print(phone('1403'))
def phone(x):
result = []
x = str(x)
for ch in x:
if ch == '0':
result.append('a')
elif ch == '1':
result.append('b')
elif ch == '3':
result.append('c')
return ''.join(result)