Handling International Dialling Codes (in Python)

The website I'm working on at the moment collects a user's phone number. This must work with phones from any country and each number must be converted into a standard format so that it can be used with an SMS API. For example, the phone number +44 (0)7912345678 would become 447912345678.

To make it as easy as possible for the user to not make a mistake, the international dialling code is in a <select>. I compiled a list* of dialling codes for all countries. In Genshi, the template code might look like this:

HTML:
  1. <select name="dialling_code">
  2.     <option py:for="country, dialling_code, ndd in internationalDiallingCodes" value="${dialling_code}">${country} (+${dialling_code})</option>
  3. </select>

When the form is submitted, we need another function to turn the dialling code plus the rest of the number into the right format (note: this is also where internationalDiallingCodes comes from):

PYTHON:
  1. def makeStandardPhoneNumber(internationalCode, rest):
  2.     """
  3.     Make a standard phone number by appending rest to the
  4.     internationalCode. Check the first digits rest to see if they
  5.     match the NDD which must be removed from the number.
  6.     i.e. 0 in the UK
  7.     Example: makeStandardPhoneNumber('44', '073749135381')
  8.         -> '4473749135381'
  9.     """
  10.     # Get the NDD code for this internationalCode
  11.     ndd = getNDD(internationalCode)
  12.  
  13.     # if the country has an NDD, check for it and remove if it
  14.     # exists
  15.     if ndd is not None:
  16.         index = len(ndd)
  17.         if rest[:index] == ndd:
  18.             rest = rest[index:]
  19.     result = internationalCode + rest
  20.     return result
  21.    
  22. def getNDD(internationalCode):
  23.     for country, iCode, ndd in internationalDiallingCodes:
  24.         if iCode == internationalCode:
  25.             return ndd
  26.     return None
  27.  
  28. internationalDiallingCodes = [
  29.     ("Afghanistan ", "93", "0"),
  30.     ("Albania", "355", "0"),
  31.     ("Algeria", "213", "7"),
  32.     ("Andorra", "376", None),
  33.     ("Angola", "244", "0"),
  34. ...
  35. ]

You can download the python source file here. It is trivial to modify the functions to put the phone number into the format you want. If you needed a performance boost, this function could be optimised by inversing the index on internationalDiallingCodes.

* Also: You can download a CSV of phone codes here. That should make it easy to include them in any program. These do not include satellite phone companies.