I am having an issue with phone number formatting in python

I am trying to format fake data from the Faker API. I am using pandas to store it into a data frame. I have figured out how to strip and replace any errors like no spacing, improper spacing, removing parenthesis, country code, and extensions. The main issue I am having is when numbers are coming out like this: xxxxxx-xxxx instead of like xxx-xxx-xxxx.

This is my code:

from faker import Faker
import pandas as pd

fake = Faker()
name = []
address = []
number = []
ssn = []

for i in range(100):
    name.append(fake.name())
    address.append(fake.address().replace('n', " "))
    ssn.append(fake.ssn())
    phone_number = fake.phone_number().split('x')[0].replace('.',"-").replace("(",'').replace(')','').replace(' ','')
    # How do to deal with the opposite of ^
    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    if phone_number.startswith('1'):
        phone_number = phone_number[1:]
    if phone_number.startswith('001'):
        phone_number = phone_number[3:]
    
    phone_number = phone_number.lstrip('-')
    
    if phone_number.isdigit() and len(phone_number) == 12: #10 or 12 work here for some reason, but I get diff. formats
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    else:
        phone_number = phone_number
    
    number.append(phone_number)

df = pd.DataFrame({'Name':name, 'Address':address,'Phone Number':number, 'SSN':ssn})
df

Not too sure where my issue is.

I initially thought it was the length or if it was being read as an int instead of a string, but when I do this:

    if phone_number.isdigit() and len(phone_number) == 12:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    elif len(phone_number) != 12:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}{phone_number[6:]}"
    else:
        phone_number = phone_number

it formats is like xxx-xxxxxxx.


If I do it this way:

    if phone_number.isdigit() and len(phone_number) == 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    elif len(phone_number) != 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}{phone_number[6:]}"
    else:
        phone_number = phone_number

then the numbers are formatted like xxx--xxx-xxxx.


    if phone_number.isdigit() and len(phone_number) == 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    else:
        phone_number = phone_number

And if I remove the elif then I get this output:’xxxxxx-xxxx’.


I am pretty much stuck and not sure what to do.

3

In this code:

    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    if phone_number.startswith('1'):
        phone_number = phone_number[1:]
    if phone_number.startswith('001'):
        phone_number = phone_number[3:]

you’re applying each test to the result of the previous assignment of phone_number. So if the phone number starts with +11, the first if block will remove +1, then the second test will succeed and remove the 1.

You should use elif so you’re only testing the original number, not making incremental checks.

    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    elif phone_number.startswith('1'):
        phone_number = phone_number[1:]
    elif phone_number.startswith('001'):
        phone_number = phone_number[3:]

Another option is to use a regular expression that removes any of these prefixes:

    phone_number = re.sub(r'^(+1|1|001)', '', phone_number)

I haven’t looked through the rest of your code, there may be more problems.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

I am having an issue with phone number formatting in python

I am trying to format fake data from the Faker API. I am using pandas to store it into a data frame. I have figured out how to strip and replace any errors like no spacing, improper spacing, removing parenthesis, country code, and extensions. The main issue I am having is when numbers are coming out like this: xxxxxx-xxxx instead of like xxx-xxx-xxxx.

This is my code:

from faker import Faker
import pandas as pd

fake = Faker()
name = []
address = []
number = []
ssn = []

for i in range(100):
    name.append(fake.name())
    address.append(fake.address().replace('n', " "))
    ssn.append(fake.ssn())
    phone_number = fake.phone_number().split('x')[0].replace('.',"-").replace("(",'').replace(')','').replace(' ','')
    # How do to deal with the opposite of ^
    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    if phone_number.startswith('1'):
        phone_number = phone_number[1:]
    if phone_number.startswith('001'):
        phone_number = phone_number[3:]
    
    phone_number = phone_number.lstrip('-')
    
    if phone_number.isdigit() and len(phone_number) == 12: #10 or 12 work here for some reason, but I get diff. formats
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    else:
        phone_number = phone_number
    
    number.append(phone_number)

df = pd.DataFrame({'Name':name, 'Address':address,'Phone Number':number, 'SSN':ssn})
df

Not too sure where my issue is.

I initially thought it was the length or if it was being read as an int instead of a string, but when I do this:

    if phone_number.isdigit() and len(phone_number) == 12:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    elif len(phone_number) != 12:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}{phone_number[6:]}"
    else:
        phone_number = phone_number

it formats is like xxx-xxxxxxx.


If I do it this way:

    if phone_number.isdigit() and len(phone_number) == 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    elif len(phone_number) != 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}{phone_number[6:]}"
    else:
        phone_number = phone_number

then the numbers are formatted like xxx--xxx-xxxx.


    if phone_number.isdigit() and len(phone_number) == 10:
        phone_number = f"{phone_number[:3]}-{phone_number[3:6]}-{phone_number[6:]}"
    else:
        phone_number = phone_number

And if I remove the elif then I get this output:’xxxxxx-xxxx’.


I am pretty much stuck and not sure what to do.

3

In this code:

    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    if phone_number.startswith('1'):
        phone_number = phone_number[1:]
    if phone_number.startswith('001'):
        phone_number = phone_number[3:]

you’re applying each test to the result of the previous assignment of phone_number. So if the phone number starts with +11, the first if block will remove +1, then the second test will succeed and remove the 1.

You should use elif so you’re only testing the original number, not making incremental checks.

    if phone_number.startswith('+1'):
        phone_number = phone_number[2:]
    elif phone_number.startswith('1'):
        phone_number = phone_number[1:]
    elif phone_number.startswith('001'):
        phone_number = phone_number[3:]

Another option is to use a regular expression that removes any of these prefixes:

    phone_number = re.sub(r'^(+1|1|001)', '', phone_number)

I haven’t looked through the rest of your code, there may be more problems.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật