将电话号码转换为电话“word”python

2024-10-01 07:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把给定的电话号码转换成相应的字母

0 -> 'a'
1 -> 'b'
2 -> 'c' etc.

例如,数字210344222应转换为字符串“cbadeeccc”。 我知道我的报税表在最后是错误的,而这正是我被卡住的地方,所以请你解释一下我将如何取而代之地返回转换后的信件

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

Tags: 字符串def地方错误字母etcphone电话号码
3条回答

有一个名为^{} in the ^{} package的常量,可用于按您描述的方式将数字转换为字母,您可以使用该数字并在ascii_lowercase中获取该索引以获取字母

from string import ascii_lowercase
phone_number = "210344222"
converted = ''.join(ascii_lowercase[int(i)] for i in phone_number)

您可以尝试使用内置的^{}方法:

def phone(x):
    return ''.join((chr(int(i) + 97)) for i in x)

print(phone('210344222'))

输出:

cbadeeccc

其中chr(97)返回'a'chr(98)返回'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'))

相关问题 更多 >