Please help with the solution of the problem. It is necessary to translate the letter designation of the number in digital. Input: 000 sinatra Output: 000 7462872

def as_numeric(text): thelist=list(text) for letters in thelist: tel_numbers={ '2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z']} if letters==tel_numbers: print(tel_numbers) else: break 

as_numeric ('000 sinatra')

    3 answers 3

    translate - returns a copy of the string in which all characters were translated using a dictionary

     phone_dict = {ord(letter): str(num) for num, le in enumerate( ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'], start=2) for letter in le} print('000 sinatra'.translate(phone_dict)) # 000 7462872 
    • Suitable use of str.translate() . You can also use dict explicitly: ''.join([letter2num.get(c, c) for c in text]) , where letter2num = {c: num for num, letters in tel_numbers.items() for c in letters} - jfs

    Corrected author code:

     def as_numeric(number): result = '' tel_numbers = {key : value for key, value in zip(range(2, 10), ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'])} for i in str(number).lower(): if i.isdigit() or i == ' ': result += i continue for key in tel_numbers.keys(): if i in tel_numbers[key]: result += str(key) return result print(as_numeric('000 sinatra')) # 000 7462872 

      tel_numbers made a reverse from the dictionary tel_numbers - phone_letter_by_num , and then it was phone_letter_by_num to compile a new line:

       def phone_as_numeric(text): phone_letter_by_num = { 'l': '5', 'b': '2', 'n': '6', 'q': '7', 'i': '4', 'j': '5', 'd': '3', 'x': '9', 'h': '4', 's': '7', 'v': '8', 'w': '9', 'g': '4', 'p': '7', 'k': '5', 'y': '9', 'u': '8', 'a': '2', 'm': '6', 'o': '6', 'e': '3', 'f': '3', 'c': '2', 'r': '7', 't': '8', 'z': '9', } new_text = '' for c in text: if c not in phone_letter_by_num: new_text += c else: new_text += phone_letter_by_num[c] return new_text print(phone_as_numeric('000 sinatra')) # 000 7462872 
      • I would like to know for what a minus. The answer is wrong or something else? :) - gil9red
      • Thank you Works. Only a small addition. And if the word is entered in capital letters? - FrankSinatra
      • @FrankSinatra, then replace for c in text: with for c in text.lower(): then the case of the letters will be unimportant - gil9red
      • Thank you for your help! - FrankSinatra
      • @FrankSinatra, then accept the answer as correct (check mark to the left of the answer) and check that the answer is useful (up arrow);) - gil9red