Problems › Python › validation
Normalise a phone number
People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.
- Throw away everything that is not a digit.
- A single leading zero is a national prefix and is dropped.
- What is left must be exactly ten digits.
- The country code must itself be one to three digits.
- The result is a plus sign, the country code, then the ten digits. Anything that does not fit gives null.
normalise_phone(raw: string, country_code: string) → string?
Where you start
def normalise_phone(raw: str, country_code: str) -> str | None:
Worked examples
| Call | Result |
|---|---|
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