converting individual digits to string

后端 未结 4 961
感动是毒
感动是毒 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:10

    phone_number = '941-019-aBcD'
    
    # A map of what letters to convert to what digits.
    #  I've added q and wxy & z.
    digit_map = {
        'abc': 2,
        'def': 3,
        'ghi': 4,
        'jkl': 5,
        'mno': 6,
        'pqrs': 7,
        'tuv': 8,
        'wxyz': 9
    }
    
    # Break this out into one letter per entry in the dictionary
    #  to make the actual work of looking it up much simpler.
    #  This is a good example of taking the data a person might
    #  have to deal with and making it easier for a machine to
    #  work with it.
    real_map = {}
    for letters, number in digit_map.iteritems():
        for letter in letters:
            real_map[letter] = number
    
    # Empty new variable.
    numeric_phone = ''
    # For each character try to 'get' the number from the 'real_map'
    #  and if that key doesn't exist, just use the value in the
    #  original string. This lets existing numbers and other
    #  characters like - and () pass though without any special
    #  handling.
    # Note the call to `lower` that converts all our letters to
    #  lowercase. This will have no effect on the existing numbers
    #  or other speacial symbols.
    for ch in phone_number.lower():
        numeric_phone += str(real_map.get(ch, ch))
    
    print(numeric_phone)
    

提交回复
热议问题