This might be redundant for your use case if all your numbers are formatted the same way, but you might consider using the phonenumbers module. This will allow you to easily add functionality (for example, international phone numbers, various formatting, etc.).
You can analyze your numbers as follows:
>>> 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 can do this:
>>> phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumber()) u'111-222-3333'
Please note that you can 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'
jterrace
source share