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?
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.
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.
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.
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'
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.
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