I'm trying to create a string that has a set amount of different words I include in a list, however the code I use only uses one word at random, not a different word for every word printed.
This is my code:
import random
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words) * 5
An example output would be:
hellohellohellohellohello
An example expected output would be:
appleyeahhellonopesomething
Can anyone tell me what I'm doing wrong?
"multiplying" a string will print the string multiple times. E.g.,
print '=' * 30
would print a line of 30"="
, that's why you are getting 5 times"hello"
- it repeats the randomly chosen word 5 times.using choice() will give you a set of 5 random selections. Note we use
sys.std.write
to the avoid the space successiveprint
statements would put between words.e.g., from two runs:
and
Of course in Python 3.x, we could use
print
instead ofsys.stdout.write
and set itsend
value to''
. I.e.,You aren't calling
random.choice(words)
5 times, you are getting an output ofrandom.choice(words)
and then multiplying in 5 times. With strings, it just repeats the string."abc" * 3
would give you"abcabcabc"
So depending on your randomly chosen word first, it just gets repeated 5 times.
If you don't want the words from your original list to be repeated, then you could use
sample
.Result:
random.choice(words) * 5
executesrandom.choice
only once and then multiplies the result by five, causing the same string to be repeated.