Reputation: 59
I recently started working with Faker because of its ability to localize data to various regions. When trying to generate localized phone numbers, I realized that there are a variety of formats for the phone numbers as seen here. I was wondering whether it would be possible for all the generated phone numbers to be formatted like this: (+91 ##########), where regardless of the country code, it remained constant. Thanks!
Upvotes: 6
Views: 18960
Reputation: 405
Unfortunately, Faker
doesn't have a built-in function to do this.
You have two options.
Write functions yourself, for example:
def fake_phone_number(fake: Faker) -> str:
return f'+91 {fake.msisdn()[3:]}'
from faker import Faker
def main():
fake = Faker()
print(fake_phone_number(fake))
Or create an appropriate provider and suggest adding it: https://faker.readthedocs.io/en/master/communityproviders.html
Python src MSISDN. What is MSISDN.
Or
from faker import Faker
from faker.providers.phone_number import Provider
class IndiaPhoneNumberProvider(Provider):
"""
A Provider for phone number.
"""
def india_phone_number(self):
return f'+91 {self.msisdn()[3:]}'
def main():
fake = Faker()
fake.add_provider(IndiaPhoneNumberProvider)
print(fake.india_phone_number())
Upvotes: 4
Reputation: 2276
You can use faker's hindi Indian provider, it will generate most of the numbers with +91, but not all:
Code sample with faker
and factoryboy.Faker
:
import factory
from faker import Faker
fake = Faker(locale="hi_IN")
fake.phone_number()
# with factory-boy's faker
class New(factory.DictFactory):
phone = factory.Faker("phone_number", locale="hi_IN")
New()
Usage result:
print(fake.phone_number())
>> +91 9018742635
print(New())
>> {'phone': '+91 1489998444'}
If you want to ensure that every number has a +91, you need to tweak with factoryboy
or wrap fake.phone_number
with a parsing function.
A neat solution could be using a library called phonenumbers like this:
import phonenumbers
from faker import Faker
fake = Faker(locale="hi_IN")
number = fake.phone_number()
num_obj = phonenumbers.parse(number, "IN")
interanational_IN_number = phonenumbers.format_number(num_obj, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
print(interanational_IN_number)
This should work most of the time, except with numbers starting with 091
- they should have two leading zero to be identified properly (0091), fix that corner case, and you should be good to go.
Upvotes: 3