Python随机模块格式

问题描述 投票:0回答:1

我有这个问题。我正在尝试在python中进行骰子滚动。但是,每当我打印它的值时,它就会附加[“”]。有什么办法可以删除?

示例。

import random

choices = ["Heads", "The Coin landed on it's side. It's a draw!", "Tails"]
rancoin = random.choices(choices, weights = [10, 1, 10], k = 1)

print("{}".format(rancoin))

输出。

[[“ Heads”],[“ Tails”]或[“ The Coin落在它的侧面。这是平局!”]

[带有额外的括号和引号真的很烦人,因为我试图将其发布到文本通道。

python random format
1个回答
0
投票

choices()返回一个列表,即使您只要求一个值。您可以通过建立索引来获取该值:

import random 

choices = ["Heads", "The Coin landed on it's side. It's a draw!", "Tails"] 
rancoin = random.choices(choices, weights = [10, 1, 10], k = 1)

print("{}".format(rancoin[0])) # note the [0] to get the first (and only) item
# Heads

您也可以将一个值拆包以达到相同的效果:

print("{}".format(*rancoin))
© www.soinside.com 2019 - 2024. All rights reserved.