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?

Will
  • 24,082
  • 14
  • 97
  • 108
Juli
  • 41
  • 1
  • 1
  • 5

1 Answers1

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))
Will
  • 24,082
  • 14
  • 97
  • 108
  • 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 – Juli Feb 20 '16 at 23:35
  • 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. – Will Feb 20 '16 at 23:36
  • With the code that I send above. How would I do that? – Juli Feb 20 '16 at 23:40
  • 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!') – Juli Feb 20 '16 at 23:45
  • 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)`). – Will Feb 20 '16 at 23:48
  • PERFECT THANK YOU SO MUCH <3 – Juli Feb 20 '16 at 23:50
  • Awesome, no problem, glad to help! :) Please click the "Accept Answer" checkbox if this solves the problem. Thanks! – Will Feb 20 '16 at 23:51