python - 不能在 .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 语句,还有哪些其他选项?
解决方案
用作randint(0,1)
获取玩家姓名的索引
players=[player1,player2]
print("{} will go first".format(players[randint(0,1)])
推荐阅读
- shopify - 如何noindex分页页面
- python-3.x - 尝试使用来自另一个表单的表单数据时,表单未通过 is_valid() 检查
- python - 在任意维数组中按元素应用 udf
- android - 是否可以在 Android 上运行 ssd_mobilenet_v1_fpn 进行推理?
- java - Jackson 和 Feign 无法反序列化 Spring 的 org.springframework.data.domain.Sort
- tensorflow - 与 pyzmq 一起使用时,Tensorflow 推理挂起
- visual-studio-code - CubeMx 生成文件不正确
- python - 在 werkzeug test_client get 方法的标头中传递 JWT 令牌
- java - Spring将字符串作为json返回,而不创建pojo进行序列化
- algorithm - 直线垂直和水平时行进广场中的插值