24 lines
829 B
Python
24 lines
829 B
Python
def normalize_phone(phone: str) -> str:
|
|
"""Normalize phone number to a canonical 09XXXXXXXXX format for Iranian numbers.
|
|
Handles +98, 0098, 9, and 09 prefixes by focusing on the last 10 digits.
|
|
"""
|
|
if not phone:
|
|
return ""
|
|
|
|
# Remove all non-digit characters
|
|
digits = "".join(filter(str.isdigit, phone))
|
|
|
|
# If no digits are found, return the original string stripped of whitespace.
|
|
# This handles cases like "abc" -> "abc", " " -> ""
|
|
if not digits:
|
|
return phone.strip()
|
|
|
|
# Standard Iranian mobile numbers end with 10 digits starting with '9'
|
|
# Example: 9123456789. We want to normalize this to 09123456789.
|
|
if len(digits) >= 10:
|
|
suffix = digits[-10:]
|
|
if suffix.startswith("9"):
|
|
return "0" + suffix
|
|
|
|
return digits
|