3

I want to create a code that would generate number of random strings (for eg.10 in this case). I used the code below but the code kept on generating same strings

Input Code

import random
import string

s = string.ascii_lowercase
c = ''.join(random.choice(s) for i in range(8))

for x in range (0,10):
    print(c)

Output

ashjkaes
ashjkaes
ashjkaes
ashjkaes
ashjkaes
ashjkaes
ashjkaes
ashjkaes
press any key to continue .....

Please help

Aryaj Pandey
  • 51
  • 1
  • 8
  • 7
    You need to put the `random.choice` in the `for` loop to make a new one each time. – Mark May 11 '19 at 18:19

5 Answers5

7

What you do now is you generate a random string c then print it 10 times You should instead place the generation inside the loop to generate a new string every time.

import random
import string

s = string.ascii_lowercase

for i in range(10):
    c = ''.join(random.choice(s) for i in range(8))
    print(c)
David Sidarous
  • 1,202
  • 1
  • 10
  • 25
  • 1
    There is no guarantee that the strings will be unique. While pretty low, there is a chance a string will be generated twice – Tomerikoo May 30 '21 at 11:42
2

Since Python 3.6, you can use random.choices (see this answer). Example:

import random
import string

sample = "".join(random.choices(string.ascii_lowercase, k=10))
print(sample)
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
2

As already noted, you need to have random.choice inside loop, what I want to note, that you could use underscore (_) meaning I do not care for that variable together with for, which in this case would mean:

import random
import string

s = string.ascii_lowercase
for _ in range(10):
    c = ''.join(random.choice(s) for _ in range(8))
    print(c)

I do not want you to feel obliged to do so, but be aware about such convention exist in Python language.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

Try below to achieve result what you want

import random
import string

s = string.ascii_lowercase

for x in range (0,10):
    print(''.join(random.choice(s) for i in range(8)))
VRAwesome
  • 4,721
  • 5
  • 27
  • 52
DoomSkull
  • 36
  • 4
1

This will give you random string including numbers, uppercase and lowercase letters.

import string, random
random_string=''
for x in range(8):
    if random.choice([1,2]) == 1:
        random_string += random_string.join(random.choice(string.ascii_letters))
    else:
        random_string += random_string.join(random.choice(string.digits))
print(random_string)
Hass786123
  • 666
  • 2
  • 7
  • 16