Phonenumbers Module in Python


Introduction

The parsing, formatting, and validation of phone numbers are made easier with the Python phonenumbers package. This module gives developers a robust set of tools to handle phone numbers in a standardized manner because it is based on Google's libphonenumber package. The phonenumbers module may extract phone numbers from user inputs, verify their accuracy, and format them in accordance with international standards.

In this post, we'll examine the numerous features and capabilities that the phonenumbers module has to offer and go into real−world applications to show how to use them. We will explore the features of this module and explain how it may make phone number handling in your Python applications simpler, from parsing and validation to formatting and extracting crucial information.

Phonenumbers Module Implementation in Python

Installation and Importing

The phonenumbers module has to be installed and loaded into our Python environment before we can explore its features. Using pip, Python's package installer, the module may be set up. After installation, we can use the import statement to add the phonenumbers module to our interactive Python sessions or scripts.

Example

pip install phonenumbers import 
phonenumbers 

Output

Looking 	in 	indexes: 	https://pypi.org/simple, 	https://us-python.pkg.dev/colabwheels/public/simple/ 
Collecting phonenumbers 
  Downloading phonenumbers-8.13.11-py2.py3-none-any.whl (2.6 MB) 
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.6/2.6 
MB 37.6 MB/s eta 0:00:00 
Installing collected packages: phonenumbers 
Successfully installed phonenumbers-8.13.11 

Parsing Phone Numbers

One of the primary tasks of the phonenumbers module is to parse phone numbers from various string representations. Whether the phone number is entered with or without the country code, with or without dashes or spaces, the parse() function provided by the module can intelligently interpret and parse the phone number. The parsed phone number object contains valuable information such as the country code, national number, extension, and more.

Example

import phonenumbers 
 
# Parse a phone number number = "+14155552671"
 parsed_number = phonenumbers.parse(number, 
None) 
 
# Accessing parsed information 
print(parsed_number.country_code)  # Output: 1 
print(parsed_number.national_number)  # Output:4155552671 
print(parsed_number.extension)  # Output: None 

Output

1 
4155552671 
None 

Validation of Phone Numbers

Validating phone numbers is crucial to ensure that they adhere to the correct format and are potentially reachable. The phonenumbers module provides various validation methods to check if a phone number is valid or possible. The is_valid_number() function determines if the phone number is valid based on its syntax and structure. On the other hand, the is_possible_number() function checks if the phone number is potentially valid, meaning it has a valid country code but may not necessarily conform to all the rules for a valid number.

Example

import phonenumbers 
 
# Validate phone numbers 
valid_number = "+14155552671" invalid_number 
= "+1234567890" 
 
print(phonenumbers.is_valid_number(phonenumbers.parse(valid_number)))  # Output: True 
print(phonenumbers.is_valid_number(phonenumbers.parse(invalid_number)))  # Output: False 
 
print(phonenumbers.is_possible_number(phonenumbers.parse(valid_number))) 	 	
# Output: True 
print(phonenumbers.is_possible_number(phonenumbers.parse(invalid_number))) 	 	# 
Output: True 

Output

True 
False 
True 
False 

Formatting Phone Numbers

It's crucial to format phone numbers consistently and uniformly before showing them to people or keeping them in a database. To guarantee that phone numbers are shown appropriately, the phonenumbers module provides a number of formatting choices.

You may format a parsed phone number using the format_number() method in accordance with many styles, including the international format, the national format, and the E.164 format. The national format just provides the national significant number without the country code, but the international format also includes the country code. The country code and national significant number are included in the E.164 format, which is standardized and does not use any formatting symbols.

Example

import phonenumbers 
 
# Format phone numbers parsed_number = phonenumbers.parse("+14155552671") 
 
# Format as international format print(phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)) 
 
# Format as national format 
print(phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.NATIONAL)) 
 
# Format as E.164 format 
print(phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.E164)) 

Output

+1 415-555-2671 
(415) 555-2671 
+14155552671 

Extracting Information from Phone Numbers

You may gather important data from phone numbers using the phonenumbers module. For instance, you may use the geocoder module, a phonenumbers submodule, to determine the location of a phone number. This capability is very helpful in applications when you need to know which nation, region, or carrier a phone number belongs to.

Example

import phonenumbers from 
phonenumbers import geocoder 
 
# Parse a phone number number = "+14155552671" parsed_number = phonenumbers.parse(number, 
None) 
 
# Retrieve the geographic information location = geocoder.description_for_number(parsed_number, "en") 
print(location)  # Output: United States 

Output

San Francisco, CA 

Advanced Usage: Geocoding and Carrier Lookup

With the help of the phonenumbers module's sophisticated capabilities, such carrier lookup and geocoding, you may learn more about phone numbers. The geocoder submodule offers tools for locating the nation, area, and carrier connected to a phone number.

A phone number's carrier or service provider may be found using the carrier submodule's capabilities. Applications that need carrier−specific functionality or that have to verify carrier data may find this handy.

Example

import phonenumbers from phonenumbers 
import geocoder, carrier 
 
# Parse a phone number number = "+14155552671"
 parsed_number = phonenumbers.parse(number,None) 
 
# Retrieve the carrier information carrier_name = carrier.name_for_number(parsed_number, "en") 
print(carrier_name)  # Output: AT&T Mobility 
 
# Retrieve the geographic information location = geocoder.description_for_number(parsed_number, "en")
 print(location)  # Output: United States 

Output

‘***’ # cannot be disclosed 
San Francisco, CA 

Handling International Phone Numbers

The phonenumbers module also provides functionality to handle international phone numbers. It allows you to determine the region or country of a phone number and format it according to the conventions of that region. This is particularly useful when working with phone numbers from different countries.

Example

import phonenumbers 
 
# Parse a phone number number = "+353876543210" 
parsed_number = phonenumbers.parse(number, None) 
 
# Get the region information 
region = phonenumbers.region_code_for_number(parsed_number) 
print(region)  # 

Output

IE

Customization and Localization

Python's phonenumbers module provides customisation possibilities to meet unique needs. By creating new information or importing metadata for particular locations, you may alter how the module behaves. This enables you to manage phone numbers that the usual metadata might not be able to handle. You may expand the functionality of the module to support special phone number formats or numbering plans by providing additional information.

Moreover, the phonenumbers module supports localization, enabling you to display phone numbers in different languages and formats. You can specify the desired language when formatting phone numbers, ensuring that the output adheres to the conventions of the specified language. This localization feature is particularly useful in applications with a global user base, as it enhances the user experience by presenting phone numbers in a familiar and appropriate format for each locale.

Best Practices and Considerations

Privacy and security concerns must be taken into account while working with sensitive user data. Adhere to applicable data protection laws and take the necessary precautions to preserve phone numbers. Put the appropriate precautions in place to prevent abuse or illegal access to phone number information.

Conclusion

The phonenumbers module in Python is a powerful and convenient tool for parsing, validating, formatting, and managing phone numbers. Its extensive range of functionalities, including parsing phone numbers in various formats, validating their correctness, and performing advanced operations like geocoding and carrier lookup, makes it an invaluable asset for applications that handle phone numbers. With its support for international phone numbers, customization options, and localization features, the phonenumbers module provides a comprehensive solution for phone number management. By leveraging this module, developers can ensure accurate and consistent handling of phone numbers in their Python projects, enhancing functionality, user experience, and data integrity.

Updated on: 25-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements