In: Computer Science
PYTHON:
Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent. For example, if the user enters 555-GET-FOOD, the application should display 555-438-3663.
This is my code, but I cannot figure out where to go from here.
#set new number
new_number = ""
#split number
split_num = phone.split("-")
for char in split_num[1:2]:
for x in "ABC":
if x == "A" or x == "B" or x == "C":
num = "2"
elif x == "D" or x == "E" or x == "F":
num = "3"
elif x== "G" or x == "H" or x == "I":
num = "4"
elif x == "J" or x == "K" or x == "L":
num = "5"
elif x == "M" or x == "N" or x == "O":
num = "6"
elif x == "P" or x == "Q" or x == "R" or x == "S":
num = "7"
elif x == "T" or x == "U" or x == "V":
num = "8"
elif x == "W" or x == "X" or x == "Y" or x == "Z":
num = "9"
else:
num = x
new_number += num
print(new_number)
Here is the solution to the above problem:
#ask the user for the input
number = input("Enter the number: ")
#split it using the split method
actualNum = number.split("-")
finalNum =""
#now the actualNum is an array of string, we need to handel each separetely
for chunk in actualNum:
for i in range(0,len(chunk)):
#thanks to you we can we this logic directly from the question provided
x = chunk[i]
if x == "A" or x == "B" or x == "C":
finalNum = finalNum + "2"
elif x == "D" or x == "E" or x == "F":
finalNum = finalNum + "3"
elif x== "G" or x == "H" or x == "I":
finalNum = finalNum + "4"
elif x == "J" or x == "K" or x == "L":
finalNum = finalNum + "5"
elif x == "M" or x == "N" or x == "O":
finalNum = finalNum + "6"
elif x == "P" or x == "Q" or x == "R" or x == "S":
finalNum = finalNum + "7"
elif x == "T" or x == "U" or x == "V":
finalNum = finalNum + "8"
elif x == "W" or x == "X" or x == "Y" or x == "Z":
finalNum = finalNum + "9"
else:
finalNum = finalNum + x
finalNum = finalNum + "-"
#this is to remvoe the last character from the string which is -
finalNum = finalNum[:-1]
print(finalNum)
Here is the output of the above code: