使用lower()进行不区分大小写的字典检查

2024-05-16 19:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用lower(),因此角色名不区分大小写。因此,如果用户键入lol而不是LoL,则不会执行if语句if not role_id:

我就是这么做的:

@commands.command()
@commands.check(lambda ctx: ctx.channel.id in [555844758778544160])
async def add(self, ctx, *, rolename):
    author = ctx.message.author
    role_dict = {
        "Members":557212810468392970,
        "PS4":568761643916328960,
        "LoL":559792606364565505}
    role_id = role_dict.get(rolename.lower())
    if not role_id:
        await ctx.send("I cannot find the role {}.".format(rolename))
        return
    role = discord.utils.get(ctx.message.guild.roles, id = role_id)
    message = '{} added the role **{}**'.format(author.display_name, role.name)
    embed = discord.Embed(description=message.format(author.display_name, role.name), colour=0xff0000)
    await author.add_roles(role)
    await ctx.send("Role Added")

这里的这一行role_id = role_dict.get(rolename.lower())是我添加角色!add lol而不是LoL的罪魁祸首。这就是我得到的:

非常感谢你的帮助。你知道吗


Tags: nameaddidformatmessagegetifawait
1条回答
网友
1楼 · 发布于 2024-05-16 19:05:26

问题是您将小写的rolename与非小写的字典键进行比较。对于不区分大小写的检查,rolename和dictionary键都应该是小写的。你知道吗

手动将字典键更改为小写:

role_dict = {
        "members":557212810468392970,
        "ps4":568761643916328960,
        "lol":559792606364565505}

或者使用dict理解以编程方式创建它,并检查rolename.lower()是否为小写dict:

role_dict = {
        "Members":557212810468392970,
        "PS4":568761643916328960,
        "LoL":559792606364565505}
lowercase_dict = {k.lower():v for k,v in role_dict.items()}
role_id = lowercase_dict.get(rolename.lower())
if not role_id:
    await ctx.send("I cannot find the role {}.".format(rolename))
    return

相关问题 更多 >