I'm currently writing a program that taking the alphanumeric phone number from a user in the format XXX-XXX-XXXX and translate it to normal phone number, based on this screenshot.
I'm trying to check if the user's input contains only alphanumeric characters, but the code I'm doing below is set for checking only letters or only numbers, as the alphanumeric phone number may have both. The program should print out the translated phone number in that format too. Here's my code:
phoneSize = 12
print("Telephone Number Translator")
telephone_number = input("Enter a 10 digit alphanumeric phone number to translate (XXX-XXX-XXXX): ")
telephone_number = telephone_number.upper()
if telephone_number.isalnum():
print("Alphanumeric input is checked.")
else:
print("Invalid input. Enter only numbers or only letters. Please restart.")
exit()
position = telephone_number.find("-")
if position == 3 and position == 7:
print("Valid input.")
else:
print("Invalid input. Enter the hyphens as the format. Please restart.")
exit()
telephone_size = len(telephone_number)
if telephone_size < phoneSize:
print("Invalid phone number. There are less than 12 characters in the phone number. Please restart.")
exit()
else:
ph_number = telephone_number[:12]
for ch in ph_number:
if "A" or "B" or "C" in ph_number:
new_str = ph_number.replace(ch, "2")
if "D" or "E" or "F" in ph_number:
new_str = ph_number.replace(ch, "3")
if "G" or "H" or "I" in ph_number:
new_str = ph_number.replace(ch, "4")
if "J" or "K" or "L" in ph_number:
new_str = ph_number.replace(ch, "5")
if "M" or "N" or "O" in ph_number:
new_str = ph_number.replace(ch, "6")
if "P" or "Q" or "R" or "S" in ph_number:
new_str = ph_number.replace(ch, "7")
if "T" or "U" or "V" in ph_number:
new_str = ph_number.replace(ch, "8")
if "W" or "X" or "Y" or "Z" in ph_number:
new_str = ph_number.replace(ch, "9")
print("The translated phone number is:",new_str)
On the other hand, I don't know why I can't check if the hyphens are correctly set in string as it keeps saying invalid input, no matter what position I enter.
Also, if I erase the alphanumeric and hyphens checking parts, the program still works, but it only formats the last character in the string to exactly number 9, and ignore the other letters in the string.