ssithuxx
ssithuxx

Reputation: 19

Generate random message from a list

I'm using this Python code to pick 3 words to form a message from the 5 words randomly.

def randomMessage():    
    word = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird']

    return (random.sample(word, 3))

and then, in a later part of the code, I want to put this in a message using

" + randomMessage() + "

but it gives me an error saying "must be str, not a list".

How can I fix this?

Upvotes: 0

Views: 3744

Answers (2)

Ursus
Ursus

Reputation: 30071

Your method returns a list, not a string. The quickest way to fix it

return " ".join(random.sample(word, 3))

Or you can make it more explicit

def random_message(): 
  words = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird']
  three_words = random.sample(words, 3)
  return " ".join(three_words)

Note: use this style in Python: random_message, not camelcase randomMessage

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20434

You need to use str.join on the list.

Calling random.sample(word, 3) returns a list, so to convert it to a string, with spaces between every element, you need to do something like:

' '.join(random.sample(word, 3))

which would give:

>>> ' '.join(random.sample(word, 3))
'Bird Dog Cat'

So, to complete the answer, you would need to modify the line at the end of your randomMessage() function, making the whole thing:

def randomMessage():
    word = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird']
    return ' '.join(random.sample(word, 3))

and some tests show that it now returns a string:

>>> randomMessage()
'Animal Queen Bird'
>>> randomMessage()
'Cat Dog Animal'
>>> randomMessage()
'Animal Cat Bird'
>>> randomMessage()
'Bird Dog Animal'

Upvotes: 3

Related Questions