Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format an un-decorated phone number in django?

I've got a DB chock full o' phone numbers as strings, they're all formatted like 1112223333, I'd like to display it as 111-222-3333 in my django template

I know I can do

n = contacts.objects.get(name=name)
n.phone = n.phone[:3] + '-' + n.phone[3:6] + '-' + n.phone[6:]

but is there a better / more pythonic way?

like image 478
JKirchartz Avatar asked Sep 08 '11 20:09

JKirchartz


2 Answers

It may be overkill for your use case if all your numbers are formatted the same way, but you might consider using the phonenumbers module. It would allow you to add functionality (e.g. international phone numbers, different formatting, etc) very easily.

You can parse your numbers like this:

>>> import phonenumbers
>>> parsed_number = phonenumbers.parse('1112223333', 'US')
>>> parsed_number
PhoneNumber(country_code=1, national_number=1112223333L, extension=None, italian_leading_zero=False, country_code_source=None, preferred_domestic_carrier_code=None)

Then, to format it the way you want, you could do this:

>>> phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumber())
u'111-222-3333'

Note that you could easily use other formats:

>>> phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.NATIONAL)
u'(111) 222-3333'
>>> phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
u'+1 111-222-3333'
>>> phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.E164)
u'+11112223333'
like image 95
jterrace Avatar answered Sep 28 '22 15:09

jterrace


Just one other solution:

n.phone = "%c%c%c-%c%c%c-%c%c%c%c" % tuple(map(ord, n.phone))

or

n.phone = "%s%s%s-%s%s%s-%s%s%s%s" % tuple(n.phone)
like image 39
rumpel Avatar answered Sep 28 '22 14:09

rumpel