如何去除Python Discord机器人中random.sample输出的括号、引号与逗号
问题原因
random.sample() 方法返回的是列表类型,直接传入Embed的description参数时,程序会自动将列表转为字符串格式,因此会额外显示列表的方括号、元素引号和逗号分隔符。
解决方案
将random.sample()返回的列表用字符串拼接方法处理后再传入description即可,推荐使用换行符拼接让两个结果分行展示,视觉效果更清晰。
修改后的代码如下:
@client.command() async def b(ctx): bishops = [ 'Bishop', 'Atomic Bishop', 'Lite Bishop', 'Crowding Bishop','Phantom Bishop', 'Sweeping Bishop', 'Ghost Bishop', 'Super Bishop','Murderous Bishop', 'Castler Bishop', 'Princess', 'Bouncing Bishop' ] # 用换行符拼接列表元素,去掉列表自带的格式符号 selected_bishops = '\n'.join(random.sample(bishops, 2)) embed = discord.Embed(title="Random Bishops", description=selected_bishops) await ctx.send(embed=embed)
如果需要两个结果用空格分隔而非换行,把代码中的'\n'替换为' '即可。
内容的提问来源于stack exchange,提问作者Jayvan
相关产品推荐
相关产品推荐

