Tuesday, 1 April 2008

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 name="dialling_code">
<option
for="country, dialling_code, ndd in internationalDiallingCodes"
value="${dialling_code}">
${country} (+${dialling_code})
</option>
</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):


def makeStandardPhoneNumber(internationalCode, rest):
"""
Make a standard phone number by appending rest to the
internationalCode. Check the first digits rest to see if they
match the NDD which must be removed from the number.
i.e. 0 in the UK
Example: makeStandardPhoneNumber('44', '073749135381')
-> '4473749135381'
"""
# Get the NDD code for this internationalCode
ndd = getNDD(internationalCode)
# if the country has an NDD, check for it and remove if it
# exists
if ndd is not None:
index = len(ndd)
if rest[:index] == ndd:
rest = rest[index:]
result = internationalCode + rest
return result

def getNDD(internationalCode):
for country, iCode, ndd in internationalDiallingCodes:
if iCode == internationalCode:
return ndd
return None

internationalDiallingCodes = [ ("Afghanistan ", "93", "0"), ("Albania", "355", "0"), ("Algeria", "213", "7"), ("Andorra", "376", None), ("Angola", "244", "0"),...]

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.

No comments: