如何从列表中保存随机字符串,以便我可以在以后的代码中回忆一下确切的事情?例如:
name = ['Hans', 'Peter', 'Eliza']
print('Your name is ' + random(name) + '!')
print(name)
我可以在这里使用什么代替random(name)
,我该如何保存?
答案 0 :(得分:4)
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.
另外,我会改用str.format()
:
import random
name = ['Hans', 'Peter', 'Eliza']
print('Your name is {}!'.format(random.choice(name)))
我错过了关于保存值的部分。这可以这样做:
name = ['Hans', 'Peter', 'Eliza']
random_name = random.choice(name)
print('Your name is {}!'.format(random_name))