Fix the Phone Number

Python for AIHard+10 XP+10

Fix the Phone Number

People type phone numbers in every style: 555.867.5309, (555) 867 5309, +1 555-867-5309. A booking system needs them all in one format.

Task: write format_phone(raw) that returns the number as "(555) 867-5309", or "invalid".

  1. Keep only the digits 0 to 9. Throw away everything else.
  2. If there are 11 digits and the first one is 1, drop that first 1.
  3. If there are now exactly 10 digits, return them as (AAA) BBB-CCCC: the first 3, then a space, the next 3, a dash, and the last 4.
  4. Anything else returns "invalid".

Examples

raw = "555.867.5309"
returns '(555) 867-5309'
raw = "867-5309"
returns 'invalid'

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run