1

I am looking to generate a random word list from a set of characters in python. Problem here:-

It is Generating like:- aaaaaa aaaaab aaaaac ...... So on

I want to add random function so it generate same length with randomization of alphabets it has like:- a15bef f45acd 9bbac0 ...... So on

Look With same length but random.

How to add random function to it?

#Code
import itertools

chrs = 'abcdef0123456789' # Change your required characters here
n = 6 # Change your word length here

for xs in itertools.product(chrs, repeat=n):
   print(''.join(xs))

please help me to solve it.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
Raj Tekken
  • 13
  • 1
  • 3
  • Raj - asked & answered here: https://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python – keithpjolley Sep 16 '18 at 11:37
  • Possible duplicate of [Generate a random letter in Python](https://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python) – Vineeth Sai Sep 16 '18 at 11:38
  • Possible duplicate of https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python – Sruthi Sep 16 '18 at 11:39

4 Answers4

2

itertools.product will generate all the possible values. Instead, what you want is to pick n random characters from chrs and concatenate them:

import random

chrs = 'abcdef0123456789' # Change your required characters here
n = 6 # Change your word length here

print(''.join(random.choices(chrs, k=5)))
Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
1

You can do it by random.choice:

import random
chrs = 'abcdef0123456789'
n = 6
result = ''.join(random.choice(chrs) for _ in range(n))
Peyman.H
  • 1,819
  • 1
  • 16
  • 26
0
''.join(random.choice(‘abcdef0123456789’) for _ in range(N))

A cryptographical more secure option is here, below example will generate random string using all undercase alphabets and digits

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
Alex
  • 1,406
  • 2
  • 18
  • 33
0

I use something like this

import random
def generateAWord (length):
    i = 0
    result = ""
    while i < length:
        letter = chr(33 + int(93 * random.random()))
        result += letter
        i +=1
    return result

33 in inside chr is the first ascii decimal that you want( 33 represent {!}). random.random() return the next random floating point number in the range [0.0, 1.0] so it times that 0.0 - 1.0 by 93 for example 0.1732*93 will result 16,1076 (and it cast that to int, so it will end as 16). So 93 represent the max result from the starting ascii decimal that you want(in this case 33) until the max ascii decimal that you want(in this case 33+93 is 126 which is {~} in ascii decimal).

Then chr will convert that result to char.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Christophorus Reyhan
  • 1,109
  • 1
  • 7
  • 14