Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't python phonenumbers library work in this case?

It seems like '5187621769' should be a very easy number for the phonenumbers library to parse. It's 10 digits with a US area code. But...no luck.

Setup:

import phonenumbers
number = '5187621769'

Method 1:

parsed = phonenumbers.parse(number)

This throws an error.

Method 2:

parsed = phonenumbers.parse("+" + number)

Gives country code = 51, which is not US.

I know I can do:

parsed = phonenumbers.parse(number,region="US")

But I don't always know the number will be US (this is just one case where I discovered I wasn't getting desired behavior). Is there an option or formatting trick I'm missing? Thanks!

like image 256
exp1orer Avatar asked Feb 04 '15 22:02

exp1orer


People also ask

What is phonenumbers library in Python?

Phonenumbers is an open-source Python library that is used for accessing information for phone numbers. It also helps in validating a phone number, parsing a phone number, etc. In this article, we will explore Phonenumbers and their functionalities.

How do you input a phone number in Python?

1. Convert String to phonenumber format: To explore the features of phonenumbers module, we need to take the phone number of a user in phonenumber format. Here we will see how to convert the user phone number to phonenumber format. Input must be of string type and country code must be added before phone number.


2 Answers

You should simply use:

parsed = phonenumbers.parse(number, 'US')
like image 98
Ludovic Gasc - GMLudo Avatar answered Nov 14 '22 23:11

Ludovic Gasc - GMLudo


It would a very easy number if phonenumbers was an US only library. You are missing the "+1" a.k.a. country code. If you would like to assume that numbers that phonenumbers can't parse are US numbers you could do something like:

try:
    parsed = phonenumbers.parse(number)
except phonenumbers.NumberParseException as npe:
    parsed = phonenumbers.parse('+1{}'.format(number))
like image 43
Ricardo Gemignani Avatar answered Nov 14 '22 21:11

Ricardo Gemignani