Phonenumbers Lite

9.0.27 · active · verified Fri Apr 10

Phonenumberslite is a Python port of Google's `libphonenumber` library, designed for parsing, formatting, storing, and validating international phone numbers. It is a 'lite' version of the main `phonenumbers` library, specifically omitting the larger geocoding, carrier, and timezone data packages to reduce its footprint, making it suitable for environments with memory or space limitations. The library is actively maintained, with the current version being 9.0.27.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse, validate, and format phone numbers using `phonenumberslite`. It shows how to handle numbers with and without explicit region codes, checks for validity and possibility, and formats numbers into E.164, International, and National formats. It also includes error handling for `NumberParseException` when an invalid string is provided.

import phonenumbers
from phonenumbers import PhoneNumberFormat
from phonenumbers.phonenumberutil import NumberParseException

# Parse a phone number
try:
    # Example with explicit region code for a non-E.164 number
    number_str_gb = "020 7946 0958"
    parsed_number_gb = phonenumbers.parse(number_str_gb, "GB")
    print(f"Parsed GB Number: {parsed_number_gb}")

    # Example with E.164 format (no region needed)
    number_str_e164 = "+15555551234"
    parsed_number_e164 = phonenumbers.parse(number_str_e164, None)
    print(f"Parsed E164 Number: {parsed_number_e164}")

    # Validate the number
    is_valid = phonenumbers.is_valid_number(parsed_number_gb)
    is_possible = phonenumbers.is_possible_number(parsed_number_gb)
    print(f"Is GB number valid? {is_valid}")
    print(f"Is GB number possible? {is_possible}")

    # Format the number
    formatted_e164 = phonenumbers.format_number(parsed_number_gb, PhoneNumberFormat.E164)
    formatted_international = phonenumbers.format_number(parsed_number_gb, PhoneNumberFormat.INTERNATIONAL)
    formatted_national = phonenumbers.format_number(parsed_number_gb, PhoneNumberFormat.NATIONAL)
    
    print(f"Formatted E.164: {formatted_e164}")
    print(f"Formatted International: {formatted_international}")
    print(f"Formatted National: {formatted_national}")

    # Attempt to parse an invalid number
    invalid_number_str = "not a phone number"
    phonenumbers.parse(invalid_number_str, "US")

except NumberParseException as e:
    print(f"Error parsing number: {e.args[0]}")

view raw JSON →