converting individual digits to string

后端 未结 4 884
感动是毒
感动是毒 2021-01-28 11:38

I think i\'m very close but i cant seem to fix my issues. I need a function that takes a 10-digit input from user (me) and sets each letter to is numeric value.

Example:

4条回答
  •  孤城傲影
    2021-01-28 12:25

    I think it's easiest to pre-calculate the number character for each letter.

    # len(keys) == 26 so that the index of a letter
    # maps to its phone key
    keys =           ['2']*3 + ['3']*3 \
         + ['4']*3 + ['5']*3 + ['6']*3 \
         + ['7']*4 + ['8']*3 + ['9']*4
    
    def letter_to_key(x):
        if x.isalpha():
            # calculate the 'index' of a letter.
            # a=0, b=1, ..., z=25
            index = ord(x.lower()) - ord('a')
            return keys[index]
        # If it's not a letter don't change it.
        return x
    
    def translate_digits(phone_num):
        return ''.join(map(letter_to_key, phone_num))
    
    print(translate_digits('941-019-abcd'))
    

提交回复
热议问题