Last modified: Nov 08, 2024 By Alexander Williams

Working with Phone Numbers in Python: A Complete Guide

Phone number handling is crucial in many applications. Python's phonenumbers library offers robust solutions for working with international phone numbers, making validation and formatting tasks easier.

Installing the phonenumbers Library

First, install the phonenumbers library using pip:


pip install phonenumbers

Basic Phone Number Parsing

The parse function is fundamental for working with phone numbers. Here's how to parse a phone number:


import phonenumbers

phone_number = "+1234567890"
parsed_number = phonenumbers.parse(phone_number)
print(parsed_number)

Validating Phone Numbers

Use is_valid_number to check if a phone number is valid. For more complex validation needs, you might want to check our detailed guide on phone number extraction.


from phonenumbers import is_valid_number

number = phonenumbers.parse("+442083661177")
is_valid = is_valid_number(number)
print(f"Is valid: {is_valid}")

Getting Country Information

You can extract country information from phone numbers. Learn more about getting country information from phone numbers.


from phonenumbers import geocoder

number = phonenumbers.parse("+442083661177")
country = geocoder.description_for_number(number, "en")
print(f"Country: {country}")

Formatting Phone Numbers

The format_number function helps format phone numbers in different styles:


from phonenumbers import format_number, PhoneNumberFormat

number = phonenumbers.parse("+442083661177")
international = format_number(number, PhoneNumberFormat.INTERNATIONAL)
national = format_number(number, PhoneNumberFormat.NATIONAL)
print(f"International: {international}")
print(f"National: {national}")

Extracting Numbers from Text

To extract phone numbers from text files or strings, use the PhoneNumberMatcher. See our guide on extracting phone numbers from text files.


from phonenumbers import PhoneNumberMatcher

text = "Call me at +1234567890 or +442083661177"
matches = PhoneNumberMatcher(text, "GB")
for match in matches:
    print(match.number)

Error Handling

Always implement proper error handling when working with phone numbers:


try:
    number = phonenumbers.parse("+invalid")
except phonenumbers.NumberParseException as e:
    print(f"Error: {e}")

Conclusion

The phonenumbers library is a powerful tool for handling phone numbers in Python. It provides comprehensive functionality for validation, formatting, and geographical information extraction.

With proper implementation, you can ensure robust phone number handling in your applications, whether for web services, data processing, or contact management systems.