不区分大小写的字典检查与lower()

时间:2019-04-20 13:37:29

标签: python python-3.x discord discord.py-rewrite

我正在尝试使用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的罪魁祸首,这就是我得到的:

不胜感激。

1 个答案:

答案 0 :(得分:3)

问题在于,您正在将小写的rolename与不在小写的字典键进行比较。对于不区分大小写的检查,rolename和字典键都应小写。

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

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