Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert Letters Numbers

can somebody help me figure out how to convert a string to a number? Let's say a user inputs "1-800-Flowers" I want python to display "1-800-3569377"

All I have so far is:

userInput = input("Please enter a phone number (e.g. 1-800-Flowers): ")
phoneNum = userInput.replace('-','')

That's really all I have. Any help would be much appreciated

like image 657
Whoo Cares Avatar asked May 11 '26 08:05

Whoo Cares


2 Answers

Using str.translate:

>>> pad = ['qz', 'abc', 'def', 'ghi', 'jkl', 'mno', 'prs', 'tuv', 'wxy']
>>> letter_to_numbers = {
...     ord(ch): ord(str(i))
...     for i, chs in enumerate(pad, 1)
...     for ch in chs
... } # Map ord('f') to ord('3'), ...
>>> "1-800-Flowers".lower().translate(letter_to_numbers)
'1-800-3569377'
like image 76
falsetru Avatar answered May 14 '26 11:05

falsetru


Have a for loop that loops through the string inputted by the user and then for every letter or number, convert it into its ASCII value using the ord() function.

other=[]
userInput = input("Please enter a phone number (e.g. 1-800-Flowers): ")
for i in userInput:
 other+=[ord(i)]

print(other)

What you were saying didn't make sense to me though, as "1-800-Flowers" does not equate to "1-800-3569377" if you convert it to ASCII, you can even check for yourself at the ASCII converter site. Do correct me if what I saying is wrong however.