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?
The output tells you exactly what's going on. chr(i) for i in random.sample(range(97, 124), 4)
is a generator. Enclose it in brackets ( print([chr(i) for i in random.sample(range(97, 124), 4])
to print the letters in a list, or use unpacking ( print(*(chr(i) for i in random.sample(range(97, 124), 4))
) to directly consume the generator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.