Python - Format Phone Number


Format Phone Number

You can format a given phone number into desired format using phonenumbers.format_number() function.

Pass the PhoneNumber object and format to phonenumbers.format_number() function, and it returns a string with given phone number in the specified format.

Some of the formats are

  • phonenumbers.PhoneNumberFormat.NATIONAL
  • phonenumbers.PhoneNumberFormat.INTERNATIONAL
  • phonenumbers.PhoneNumberFormat.E164
  • phonenumbers.PhoneNumberFormat.RFC3966

Examples

1. Format phone number to NATIONAL

In the following program, we take a phone number string, parse it to PhoneNumber object, and format this PhoneNumber object to NATIONAL format.

Python Program

import phonenumbers

#phone number in a string
phonenumber_string = "+442083661177"

#parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)

#format PhoneNumber to NATIONAL
formatted = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.NATIONAL)
print('NATIONAL Format :', formatted)

Output

NATIONAL Format : 020 8366 1177

2. Format phone number to INTERNATIONAL

In the following program, we take a phone number string, parse it to PhoneNumber object, and format this PhoneNumber object to INTERNATIONAL format.

Python Program

import phonenumbers

#phone number in a string
phonenumber_string = "+442083661177"

#parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)

#format PhoneNumber to INTERNATIONAL
formatted = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
print('INTERNATIONAL Format :', formatted)

Output

INTERNATIONAL Format : +44 20 8366 1177

3. Format phone number to E164

In the following program, we take a phone number string, parse it to PhoneNumber object, and format this PhoneNumber object to E164 format.

Python Program

import phonenumbers

#phone number in a string
phonenumber_string = "+442083661177"

#parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)

#format PhoneNumber to E164
formatted = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.E164)
print('E164 Format :', formatted)

Output

E164 Format : +442083661177

4. Format phone number to RFC3966

In the following program, we take a phone number string, parse it to PhoneNumber object, and format this PhoneNumber object to RFC3966 format.

Python Program

import phonenumbers

#phone number in a string
phonenumber_string = "+442083661177"

#parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)

#format PhoneNumber to RFC3966
formatted = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.RFC3966)
print('RFC3966 Format :', formatted)

Output

RFC3966 Format : tel:+44-20-8366-1177

Summary

In this tutorial of Python Examples, we learned how to format a given phone number using format_number() function, with the help of example programs.