samedi 9 février 2019

How can I print a random sample (with random.sample(range(x,y), z)) using a for-loop in a SINGLE line of code in Python?

I am trying to print 4 letters that are randomly selected from the alphabet. How can I accomplish this using "for" in a single line of code?

Previously I did it using a small block of code in a for-loop, but I want to do it using only a single line of code.

This is what I did in the past:

for i in random.sample(range(97, 124), 4):
    print(chr(i), end='')

OUTPUT: 'fgaj'

Now, I am trying to compress this into a single line of code, like this:

print(chr(i) for i in random.sample(range(97, 124), 4))

However, I receive the following output:

<generator object <genexpr> at 0x10d10e1b0>

Why is it not printing 4 randomly selected letters?




Aucun commentaire:

Enregistrer un commentaire