I need to create a function, where, If I give an input like 999933. It should give output as “ze”. It basically work as numeric mobile phone keypad. How can I this. I have searched to get some sample in internet. All, I got was quite opposite. Like, Giving the text as input and you will get the number. I couldn’t get the exact flow of, how to achieve that. Please let me know, how can i do that.
def number_to_text(val): pass
Advertisement
Answer
You need to
- group the same digits together with the regex
(d)1*
that capture a digit then the same digit X times - use the value of a digit in the group to get the key
- use the length of it to get the letter
phone_letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] def number_to_text(val): groups = [match.group() for match in re.finditer(r'(d)1*', val)] result = "" for group in groups: keynumber = int(group[0]) count = len(group) result += phone_letters[keynumber][count - 1] return result print(number_to_text("999933")) # ze
Using list comprehension
def number_to_text(val): groups = [match.group() for match in re.finditer(r'(d)1*', val)] return "".join(phone_letters[int(group[0])][len(group) - 1] for group in groups)