Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to format a phone number in Python?

If all I have is a string of 10 or more digits, how can I format this as a phone number?

Some trivial examples:

555-5555 555-555-5555 1-800-555-5555 

I know those aren't the only ways to format them, and it's very likely I'll leave things out if I do it myself. Is there a python library or a standard way of formatting phone numbers?

like image 336
Joe Avatar asked Aug 14 '11 16:08

Joe


People also ask

How do you format a phone number correctly?

North American phone numbers To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.

How do you clean a phone number in Python?

clean is the function that is provided by the cleantext library. To replace the phone numbers, we set the parameter no_phone_numberss to True . Then, we provide the string to replace the phone numbers. If we don't provide the string, the phone numbers will be replaced with <PHONE> by default.

How do you enter a phone number in Python?

Convert String to phonenumber format: To explore the features of phonenumbers module, we need to take the phone number of a user in phonenumber format. Here we will see how to convert the user phone number to phonenumber format. Input must be of string type and country code must be added before phone number.


2 Answers

Seems like your examples formatted with three digits groups except last, you can write a simple function, uses thousand seperator and adds last digit:

>>> def phone_format(n):                                                                                                                                   ...     return format(int(n[:-1]), ",").replace(",", "-") + n[-1]                                                                                                            ...  >>> phone_format("5555555") '555-5555' >>> phone_format("5555555") '555-5555' >>> phone_format("5555555555") '555-555-5555' >>> phone_format("18005555555") '1-800-555-5555' 
like image 33
utdemir Avatar answered Oct 11 '22 14:10

utdemir


for library: phonenumbers (pypi, source)

Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.

The readme is insufficient, but I found the code well documented.

like image 124
kusut Avatar answered Oct 11 '22 13:10

kusut