In this article we want to learn about Python Phonenumbers Library , as you know Python is one of the best language and it has a lot of different libraries for different purposes. Phonenumbers is one of the libraries that it has different features like providing basic information of a phone number, validation of a phone number etc.
Learn More on Python
Installation
It is a third party library and you need to install this library, you can use pip for the installation.
1 |
pip install phonenumbers |
Finding the format in a Phone Number.
1 2 3 4 5 6 7 8 |
import phonenumbers #parsing the phonenumber phoneNumber = phonenumbers.parse("+93748943493") #printing the phonenumber print(phoneNumber) |
You will see that we have the format for the phone number.
1 |
Country Code: 93 National Number: 748943493 |
OK now we want to create an example to get phone number from a text.
1 2 3 4 5 6 7 8 9 10 11 |
import phonenumbers text = "Contact me at +93748943493" numbers = phonenumbers.PhoneNumberMatcher(text, "AFG") for number in numbers: print(number) |
This is the result.
1 |
PhoneNumberMatch [14,26) +93748943493 |
For mobile numbers in some countries, you can also find out information about which carrier originally owned a phone number.
1 2 3 4 5 6 |
import phonenumbers from phonenumbers import carrier ro_number = phonenumbers.parse("+93748943493", "AFG") print(carrier.name_for_number(ro_number, "en")) |
Run the code and this is the result.
1 |
Afghan Telecom |
You might also be able to retrieve a list of time zone names that the number potentially belongs to.
1 2 3 4 5 6 |
import phonenumbers from phonenumbers import timezone loc_number = phonenumbers.parse("+93748943493", "AFG") print(timezone.time_zones_for_number(loc_number)) |
If your application has a UI that allows the user to type in a phone number, it’s nice to get the formatting applied as the user types. The AsYouTypeFormatter
object allows this.
1 2 3 4 5 |
import phonenumbers formatter = phonenumbers.AsYouTypeFormatter("US") print(formatter.input_digit("6")) |
This is the result.
1 |
('Asia/Kabul',) |
This was a simple example on How to Use Phonenumbers Library in Python