Drill

ProblemsPython › validation

Normalise a phone number

mediumvalidationPython

People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.

normalise_phone(raw: string, country_code: string) → string?

Solve it in the editor →

Where you start

def normalise_phone(raw: str, country_code: str) -> str | None:
    

Worked examples

CallResult
normalise_phone("0532 123 45 67", "90")"+905321234567"
normalise_phone("532-123-4567", "90")"+905321234567"
normalise_phone("(532) 123 45 67", "1")"+15321234567"
normalise_phone("123", "90")None

Hint

Clean, then drop the leading zero, then check the length. Three steps in that order.

Reference solution in Python
def normalise_phone(raw: str, country_code: str) -> str | None:
    if not 1 <= len(country_code) <= 3 or not country_code.isdigit():
        return None
    d = ''.join(c for c in raw if c.isdigit())
    if d.startswith('0'):
        d = d[1:]
    return '+' + country_code + d if len(d) == 10 else None

The same problem in another language

More validation problems in Python