Created
February 25, 2020 18:43
-
-
Save radzhome/aa1028093c5ffb6f325ffe23eff94334 to your computer and use it in GitHub Desktop.
format_phone_number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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