4

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

1
  • 7
    You need to put the random.choice in the for loop to make a new one each time. Commented May 11, 2019 at 18:19

5 Answers 5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

There is no guarantee that the strings will be unique. While pretty low, there is a chance a string will be generated twice
3

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)

Comments

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.

Comments

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)))

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.