user21143082
user21143082

Reputation: 1

Python phonenumbers: how to get the required number of digits of a mobile phone in a country?

I want to use python phonenumbers to get the number of digits that mobile phones have to have for each country.

I'm importing the phonenumbers/libphonenumber library.

I tried fetching the metadata with no success. Then I tried fetching an example number to then deduce it from there. It looks like I'm not being able to give with the adequate attributes or classes to fetch these. Do you know which are the attributes or classes I need to look for in order to get to this information?

country = phonenumbers.region_code_for_country_code(country_code)
metadata = phonenumbers.metadata_for_region(country)

or

region_code = phonenumbers.region_code_for_country_code(country_code)
example_number = phonenumbers.get_example_number_for_type(region_code, phonenumbers.PhoneNumberType.MOBILE)

I'm open to using other libraries too.

Upvotes: 0

Views: 255

Answers (1)

Laura Aguiar Martinho
Laura Aguiar Martinho

Reputation: 13

You can try this code that retrieves the required number of digits of a mobile phone number in a specific country using your database:


import sqlite3

def get_mobile_number_digits(country_code):
    # Connect to the database
    conn = sqlite3.connect("phone_number_format.db")
    cursor = conn.cursor()
    
    # Query the database for the required number of digits for the given country code
    query = "SELECT num_digits FROM phone_number_format WHERE country_code=?"
    cursor.execute(query, (country_code,))
    result = cursor.fetchone()
    
    # Close the database connection
    cursor.close()
    conn.close()
    
    # Return the result
    if result:
        return result[0]
    else:
        return None

The database phone_number_format.db has a table named phone_number_format with columns country_code and num_digits. The get_mobile_number_digits function takes a country_code as input and returns the required number of digits for that country code. If the country code is not found in the database, the function returns None.

Upvotes: -2

Related Questions