首页 > 解决方案 > 不能在 .format() 字符串中直接使用 randint() 吗?

问题描述

完整的初学者在这里。

我正在制作一个短游戏,其中随机选择两名玩家之一开始游戏:

from random import randint
player1 = input("First player, enter your name: ")
player2 = input("Second player, enter your name: ")

print("{randint(0,1)} will go first".format(name1, name2))

我希望 randint() 选择 player1 或 player2,但我得到一个 TypeError。如果我将 0 或 1 放入 {} 而不是 randint(0, 1) 它工作正常。为什么这不起作用?除了 if/elif 语句,还有哪些其他选项?

标签: pythonrandom

解决方案


用作randint(0,1)获取玩家姓名的索引

players=[player1,player2]    
print("{} will go first".format(players[randint(0,1)])

推荐阅读