当前位置:优学网  >  在线题库

在discord.py中发送消息时,如何替换某些字符

发表时间:2022-07-27 00:37:33 阅读:215

我的问题是,我正试图为我的discord bot生成一个leader board命令,但当我对json文件排序,然后显示如下消息:

{| Name:784779,|Name_1:539427,|Name_2:310407,|Name_3:280250,|Name_4:0}

它被排序了,但它看起来很凌乱,因为括号和引号,也因为它都在一行.我试图用replace()修复此问题,但出现了一个错误.有没有其他替代字符的方法?我的代码

if "!leaderboard" in message.content:
    with open("income.json", "r+") as f:
        incomes = json.load(f)
    Sort = {k: v for k, v in sorted(incomes.items(), key=lambda item: item[1], reverse= True)}

    embedVar = discord.Embed(title= "Leader board",value=(""), inline=False, color=0x71368a)
    embedVar.add_field(name=('﹉﹉﹉﹉﹉﹉﹉﹉﹉﹉﹉﹉﹉'), value=(Sort))
    await message.channel.send(embed=embedVar)
🎖️ 优质答案
  • Sort is not a string but a dictionary, that's why replace doesn't work. It gets automatically converted to a string but if you wanna format it yourself, you will have to iterate through it and convert it manually.

    my_string = ""
    for k, v in Sort.items():
        my_string += str(k) + ": " + str(v) + "\n"

    Then pass my_string to embedVar.addfield instead of passing Sort. This is the basic idea, modify it to fit your needs.

  • 相关问题