[Python] I am having an issue with phone number formatting in python

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página