Skip to content

Instantly share code, notes, and snippets.

@TMcManus
Last active May 18, 2016 23:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TMcManus/4347567 to your computer and use it in GitHub Desktop.
Save TMcManus/4347567 to your computer and use it in GitHub Desktop.
Examples of how to use the python port of libphonenumber.

The python port of libphonenumber is pretty complete, but is a little short on examples and sample code. Here are some simple examples for some common uses of this fantastic library.

import phonenumbers as ph
def example_mobile_number(country_code):
"""Returns an example mobile phone number from a country in e.164
Arguments:
country_code -- ISO 3166-1 alpha-2 code as a string
"""
number_object = ph.example_number_for_type(country_code, 1)
return ph.format_number(number_object, ph.PhoneNumberFormat.E164)
def get_country_code(phone_number):
"""Returns the ISO 3166-1 alpha-2 code for a phone number
Arguments:
phone_number -- A phone number in any format as a string
"""
number_object = ph.parse(phone_number)
return ph.region_code_for_number(number_object)
def valid_number(phone_number):
"""Returns True if the phone number can exist
Arguments:
phone_number -- A phone number in any format as a string
"""
number_object = ph.parse(phone_number)
if ph.is_valid_number(number_object):
return True
else:
return False
def valid_mobile_number(phone_number):
"""Returns True if the phone number can exist and is in the mobile range
for the country.
Arguments:
phone_number -- A phone number in any format as a string
"""
number_object = ph.parse(phone_number)
if ph.number_type(number_object) == 1:
return True
elif ph.number_type(number_object) == 2:
# This is to cover the US and Canada, where it is impossible to tell
# if a phone number is a mobile number or not from its structure.
# Other countries in the NANPA will return similar values.
return True
else:
return False
### Some Examples ###
print example_mobile_number("JP")
# "+817012345678"
print valid_number("+180855509876")
# False
print valid_number("+18085550987")
# True
print valid_mobile_number("+18085550987")
# True
print valid_mobile_number("+81312345678")
# False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment