Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility method to format phone numbers #928

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions parsons/utilities/format_phone_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import re


def format_phone_number(phone_number, country_code="1"):
"""
Formats a phone number in E.164 format, which is the international standard for phone numbers.
Example: Converts "555-555-5555" -> "+15555555555"

`Args:`
phone_number (str):
The phone number to be formatted.
country_code (str):
The country code to be used as a prefix.
Defaults to "1" (United States).

`Returns:`
str:
The formatted phone number in E.164 format.
"""
# Remove non-numeric characters and leading zeros
digits = re.sub(r"[^\d]", "", phone_number.lstrip("0"))

# Check if the phone number is valid
if len(digits) < 10:
return None

# Handle country code prefix
if not digits.startswith(country_code):
digits = country_code + digits

# Format the phone number in E.164 format
formatted_number = "+" + digits

return formatted_number
34 changes: 34 additions & 0 deletions test/test_utilities/test_format_phone_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import unittest
from parsons.utilities.format_phone_number import format_phone_number


class TestFormatPhoneNumber(unittest.TestCase):
def test_format_phone_number_local_us_number(self):
phone_number = "555-123-4567"
expected_result = "+15551234567"
self.assertEqual(
format_phone_number(
phone_number,
),
expected_result,
)

def test_format_phone_number_us_number_with_leading_1(self):
phone_number = "15551234567"
expected_result = "+15551234567"
self.assertEqual(format_phone_number(phone_number), expected_result)

def test_format_phone_number_international_number(self):
phone_number = "+441234567890"
expected_result = "+441234567890"
self.assertEqual(
format_phone_number(phone_number, country_code="44"), expected_result
)

def test_format_phone_number_invalid_length(self):
phone_number = "12345"
self.assertIsNone(format_phone_number(phone_number))


if __name__ == "__main__":
unittest.main()