I made this program to properly format a North American phone number. If its a 10-digit phone number (9999999999) it adds a 1 in the beginning and adds in dashes (1-999-999-9999). If its 11 digits (with a 1 at the beginning, 19999999999) we add in dashes (1-999-999-9999). Otherwise, its not a valid North American phone number.
def NorthAmerica(phone_number):
if phone_number.isdigit():
phone_number = phone_number
else:
raise Exception("Error in setting phone number:\n Phone number has to be numbers only")
if len(phone_number) == 10:
pass
elif len(phone_number) == 11 and str(phone_number)[0] == '1':
pass
else:
raise Exception("Error in formatting phone number as North American:\n North American phone numbers have to be 10 digits, or 11 digits with the digit before the area code being a 1")
number_list = list(phone_number)
if len(number_list) == 10:
number_list.insert(0, "1")
number_list.insert(1, "-")
number_list.insert(5, "-")
number_list.insert(9, "-")
elif len(number_list) == 11:
number_list.insert(1, "-")
number_list.insert(5, "-")
number_list.insert(9, "-")
final_number = "".join(number_list)
return final_number
Any comments or ideas on how to prove it?
phone_number = phone_number
\$\endgroup\$(609) 555-1212
. We don't use dashes except for separating the last two parts, and we typically only include the leading1
under protest as it isn't part of someone's actual phone number. Its just something the phone company makes us key in sometimes \$\endgroup\$