1

Is there a way to randomize a set string, like you can for integers?

I'll give an example:

import random
random.randint(1, 30) #will produce random number between 1 and 30

And for a string I would like to randomize words from a set variable:

a="off","it","on","not"
random.randstr(a) #I understand that this isnt a real code and will produce and error

Is there an easy way to make this possible?

1
  • 1
    replace randstr by choice and off you go. Commented Sep 13, 2013 at 22:00

2 Answers 2

16

Try this, it's the idiomatic solution:

import random
a = ['off', 'it', 'on', 'not']
random.choice(a)
=> 'on' # just an example, it's a random output

The above code makes use of the choice() function, take a look at the documentation for additional details.

Sign up to request clarification or add additional context in comments.

Comments

3

Like this:

a = ["off","it","on","not"]
a[random.randint(0, len(a))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.