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?
random.choice(words) * 5 executes random.choice only once and then multiplies the result by five, causing the same string to be repeated.
>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
If you don't want the words from your original list to be repeated, then you could use sample.
import random as rn
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
word = ''.join(rn.sample(words, 5))
Result:
>>> word
'yeahhellosomethingapplenope'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With