Skip to content

Instantly share code, notes, and snippets.

@radzhome
Created Feb 25, 2020
Embed
What would you like to do?
format_phone_number
import re
import logging
def phone_format(phone_number, raise_exception=False):
"""
Cleans up formatting for a phone number
format_phone_number
:param raise_exception: bool, throw an exception or return original value
:param phone_number: inputted raw phone
:return: str formatted_phone_number
"""
if phone_number:
try:
# Extensions not saved.
phone_number = str(phone_number).split('x')[0]
clean_phone_number = re.sub('[^0-9]+', '', phone_number)
formatted_phone_number = (re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1-", "%s" % clean_phone_number[:-1]) +
clean_phone_number[-1])
except Exception as e:
logging.error("helpers.phone_format unable to format phone: '{}'. {} {}"
"".format(phone_number, type(e).__name__, e))
if raise_exception:
raise e
formatted_phone_number = phone_number
return formatted_phone_number
else:
return phone_number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment