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!
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.
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.
You should simply use:
parsed = phonenumbers.parse(number, 'US')
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With