how to make random value in range a-z with python

Question:

I have python code which it will generate random values like

JAY5uFy4F

This is the first output when I run the python script.

This is my code:

a= []
n=1
c=1
c2=3
Start= 10**(n-1)
End= (10**n)-1
while 1 :
    Num= random.randint(Start,End)
    Text= string.ascii_letters
    txt=''.join(random.choice(Text) for i in range(c))
    txt2=''.join(random.choice(Text) for i in range(c2))

    def Value():
        V= random.randint(3,6)
        vl= (f"JAY{V}{txt2}{Num}{txt}")
        return (vl)
    passwd =Value()
    if (passwd) not in (a):
        a.append (passwd)
        print(a)
    else:
        break

I know the code above will generate the sentence "JAY…" randomly but what I want is to get [az][AZ] after the word "JAY…"

For example:

JAY5abc1d
JAY5bcd1e
JAY5cde1f

etc.
and also uppercase characters

JAY5Abc1d
JAY5Bcd1e
JAY5Cde1f

until z, then when it reaches the last character the number changes

JAY5Abc2d 
JAY5Bcd2e 
JAY5Cde2f
Asked By: DotSlash

||

Answers:

I’d use itertools.product to iterate deterministically, rather than using a randomized algorithm.

Something like would seem to do what you want:

import itertools
from string import ascii_letters

def make_options(n, c1, c2):
  parts = [
    ['JAY'],
    map(str, range(3, 7)),
    *([ascii_letters] * c1),
    map(str, range(10**(n-1), 10**n)),
    *([ascii_letters] * c2),
  ]
  for cs in itertools.product(*parts):
    yield ''.join(cs)

I’m using an iterator because this will be a long list, and trying to keep the whole thing in memory at once will probably fail.

If you keep your parameters in the small part of the space, you can easily get an array out of this by doing:

a = list(make_options(1, 1, 1))

but note that this is already 97k entries.

Answered By: Sam Mason
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.