def validate_phone_number(phone_number): formatted_number = '' split_phone = phone_number.split('x') if len(split_phone) > 1: phone_number = split_phone[0] extension = split_phone[1] else: phone_number = split_phone[0] extension = None stripped_number = re.sub(r"\D", "", phone_number) if len(stripped_number) == 10: formatted_number = "(%s%s%s) %s%s%s-%s%s%s%s" % tuple(stripped_number) elif len(stripped_number) == 11: formatted_number = "%s (%s%s%s) %s%s%s-%s%s%s%s" % tuple(stripped_number) if extension: formatted_number = formatted_number + " x" + re.sub(r"\D", "", extension) return formatted_number
2223334444 => (222) 333-4444
222 333 4444 => (222) 333-4444
12223334444 => 1 (222) 333-4444
1 222 333 4444 => 1 (222) 333-4444
12223334444x55 => 1 (222) 333-4444 x55
1 222 333 4444 x55 => 1 (222) 333-4444 x55