简体   繁体   中英

How to generate fake name using length python Faker package

I wanted to generate a fake name of length 10 using Faker python package.

from faker import Faker
fake = Faker()
print(fake.name())

it generates a fake name of any length, but I wanted to Generate a name of length 10.

is there any way to generate a name of length 10 using Faker or set length 10 before generating fake data?

No, but it is rather easy to create a generator that filters only length 10 results from Faker:

import faker, itertools

def conditional_fake(cond):
    fake = fake.Faker()
    while True:
        x = fake.name()
        if cond(x):
            yield x

# print 20 names of length 10
for n in itertools.islice(conditional_fake(lambda name: len(name)==10), 20):
    print(n)

You could write a loop:

from itertools import count
from faker import Faker

faker = Faker()

names = (faker.name() for _ in count())

name = next(name for name in names
            if len(name) == 10)

It can be simply done by this:-

fake = Faker()

fake.pystr(min_chars=None, max_chars=10)

Plz refer this for more info:- https://faker.readthedocs.io/en/master/providers/faker.providers.python.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM