2

How do I save a random string from a list so I can recall the exact thing later in the code? For example:

name = ['Hans', 'Peter', 'Eliza']
print('Your name is ' + random(name) + '!')
print(name)

What can I use here in place of random(name), and how can I save it?

0

1 Answer 1

6

You can use the choice() method from the random module:

import random

name = ['Hans', 'Peter', 'Eliza']
print('Your name is ' + random.choice(name) + '!')
random.choice(seq)
    Return a random element from the non-empty sequence seq.
    If seq is empty, raises IndexError.

Also, I would use str.format() instead:

import random

name = ['Hans', 'Peter', 'Eliza']
print('Your name is {}!'.format(random.choice(name)))

I missed the part about saving the value. That can be done like this:

name = ['Hans', 'Peter', 'Eliza']
random_name = random.choice(name)

print('Your name is {}!'.format(random_name))
Sign up to request clarification or add additional context in comments.

7 Comments

enemy = ['Zombie', 'Dragon', 'Warrior'] print('A ' + random.choice(enemy) + ' appeared!\nHealth ' + str(enemystats[0]) + '\nAttack Damage ' + str(enemystats[1]) + '\nInitiative ' + str(enemystats[2])) print('The ' + enemy + ' attacked you!') TypeError: cannot concatenate 'str' and 'list' objects
Hmm? In [10]: print('Your name is ' + random.choice(name) + '!') Your name is Hans! random.choice() will only return one element of a list. Added a note about str.format() just in case.
With the code that I send above. How would I do that?
I want to save the enemy name (Zombie, Dragon or Warrior) which will be randomly selected and then re-use the name in the variable so I can call it later with : print('The ' + enemy + 'attacked you!')
Ah, got it. See my edit in the answer. The error you were seeing about concatenating strings and lists shouldn't happen if your enemystats list is just a flat list. If it's a list of lists, or a list of other objects, you can't print them in that way (convert to string using ' '.join(my_list)).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.