Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format phone number

How would I go about formatting a 10 digit string: 0123456789 to phone number format:

(012) 345-6789

Is there a specific library to use or can you use regex?

I've done it the other way around by using re.sub('[^0-9]', '', '(012) 345-6789')

like image 972
Matrix21 Avatar asked Jul 07 '18 23:07

Matrix21


2 Answers

You can also use a library like phonenumbers?

Install it:

pip install --user phonenumbers

Code Sample:

import phonenumbers 
phonenumbers.format_number(phonenumbers.parse("0123456789", 'US'),
                           phonenumbers.PhoneNumberFormat.NATIONAL)

Output:

'(012) 345-6789'
like image 143
Rafael Avatar answered Oct 09 '22 22:10

Rafael


import re
print('(%s) %s-%s' % tuple(re.findall(r'\d{4}$|\d{3}', '0123456789')))

This outputs:

(012) 345-6789
like image 23
blhsing Avatar answered Oct 10 '22 00:10

blhsing