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'
You aren't calling random.choice(words)
5 times, you are getting an output of random.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.
"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.
import random, sys
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
for i in range(5):
sys.stdout.write(random.choice(words))
using choice() will give you a set of 5 random selections. Note we use sys.std.write
to the avoid the space successive print
statements would put between words.
e.g., from two runs:
yeahsomethinghelloyeahlalala
and
somethingyeahsomethinglalalanope
choice()
Return a random element from the non-empty sequence seq. If seq is
empty, raises IndexError.
Of course in Python 3.x, we could use print
instead of sys.stdout.write
and set its end
value to ''
. I.e.,
print(random.choice(words), end='')
import random
WORDS = ("Python","Java","C++","Swift","Assembly")
for letter in WORDS:
position = random.randrange(len(WORDS))
word = WORDS[position]
print(word)