Home > Back-end >  Randomize characters in loop [duplicate]
Randomize characters in loop [duplicate]

Time:09-22

I want to randomize the answers in my for loop. My current code only prints: AAA,BBB,CCC.

while True:
    for i in range(65,91):
        answer = chr(i)   chr(i)   chr(i)
        print(answer)

How can I randomly return every single possible combination like AXY,BMK, etc.

Is this possible with the random module or do I need to use something else?

CodePudding user response:

Try this:

import string
import random
char_big = string.ascii_uppercase

while True:
    print(''.join(random.choice(char_big) for _ in range(3)))

By thanks of @JiříBaum, if this is important for you to prevent from attack you can use SystemRandom from secrets like below:

import string
import secrets
char_big = string.ascii_uppercase

while True:
    print(''.join(secrets.choice(char_big) for _ in range(3)))

Or:

import string
import secrets
char_big = string.ascii_uppercase

while True:
    print(
        ''.join(char_big[secrets.SystemRandom().randrange(0, 26)] \
                for _ in range(3)
               )
    )
  • Related