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')
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'
import re
print('(%s) %s-%s' % tuple(re.findall(r'\d{4}$|\d{3}', '0123456789')))
This outputs:
(012) 345-6789
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With