Randomly draw letters

Asked

Viewed 4,270 times

-2

I can generate numbers, but letters how do I generate type AB BC AEEE, for example.

import random

import string

for j in range(40,100):

print(random.choice(string.ascii_uppercase))

In this code I have a lowercase letter. I need 4 letters per class number of classes from 40 to 100

  • 1

    Ever thought of calling the job random.choice 4 times?

  • it worked however they are not straight as a knife to place them in a straight line I can use print end but as ?

1 answer

2

What you need to do is basically call the function random.choice the number of times you want to draw a letter. How you need 4 letters: 4 times.

import random
import string

letras = string.ascii_uppercase

for turma in range(40, 100):
    codigo = ''.join(random.choice(letras) for _ in range(4))
    print('Turma', turma, 'possui o código', codigo)

However, this does not guarantee that the codes will be unique, with two or more classes having the same code.

  • worked out thanks

  • Complementing what Anderson said, so that the numbers do not repeat, you need to store the letters in some structure, as a list, so that your check if there is the occurrence of a certain letter inside the list. Thus eliminating the duplicity of drawn letters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.