【问题标题】:converting phone number into phone 'word' - python将电话号码转换为电话“单词” - python
【发布时间】:2021-08-18 09:42:45
【问题描述】:

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

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

【问题讨论】:

  • 是的,我知道我不会升到“4”等等,但这不是我遇到的问题,所以试图为每个人简化它

标签: python if-statement numbers return


【解决方案1】:
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)

【讨论】:

  • 我还没学过 append 是不是只用于列表?
  • 据我所知。是的
【解决方案2】:

使用 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'))

【讨论】:

    【解决方案3】:

    您可以尝试使用内置的chr() 方法:

    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 位。

    【讨论】:

      【解决方案4】:

      有一个名为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)
      

      【讨论】:

        最近更新 更多