6

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')

1
  • If you're seeking a streamlined solution for formatting phone numbers, consider trying this API! It's designed to handle a variety of formats and can easily convert a 10-digit string into the format (012) 345-6789. Check it out here: API URL. Commented Jul 14, 2024 at 14:36

6 Answers 6

9

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'
Sign up to request clarification or add additional context in comments.

Comments

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

This outputs:

(012) 345-6789

Comments

5

Using re.sub lets you handle output string formatting in a single command.

import re
s = '0123456789'

>>> re.sub(r'(\d{3})(\d{3})(\d{4})', r'(\1) \2-\3', s)
'(012) 345-6789'

Comments

3

Slice the string into the parts you need separated, such as the first three numbers for the area code, (slicing tutorial) then concatenate the parts and formatting together, (concatenation tutorial).

num="0123456789"
print("("+num[:3]+")"+num[3:6]+"-"+num[6:])

Comments

1

To enhance Mike's response a little:

def parsephone(strphone):
    '''
    Pull out just the digits. Then do some simple formating.
    '''
    phn = ""
    for n in strphone:
        if n in "0123456789":
            phn += n
    if len(phn) == 10:  # add a 1 in front
        phn = "1" + phn
    if len(phn) != 11:
        return phn  # no hope of formating
    # format with dashes
    phn = phn[:1] + "-" + phn[1:4] + "-" + phn[4:7] + "-" + phn[7:]
    return phn

Comments

1

You can use the function clean_phone() from the library DataPrep. Install it with pip install dataprep.

>>> from dataprep.clean import clean_phone
>>> df = pd.DataFrame({'phone': ['0123456789', 1234567890]})
>>> clean_phone(df, 'phone', output_format='national')
Phone Number Cleaning Report:                                                   
    2 values cleaned (100.0%)
Result contains 2 (100.0%) values in the correct format and 0 null values (0.0%)
        phone     phone_clean
0  0123456789  (012) 345-6789
1  1234567890  (123) 456-7890

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.