首页 > 解决方案 > 如何删除变量中的 {''}?

问题描述

我最近做了一个命令,将信息保存到 JSON 文件中。所以基本上,我有 2 个命令,第一个命令设置全局变量,第二个命令使用提供的变量添加到 JSON 文件中。一旦我对其进行测试,它会将文本保存为全局变量,然后将其保存为 JSON 文件{'test'}。我不想要{''},所以有没有办法没有{''},只有文字test

脚本:

#global variables
namereg = None
cbreg = None #more
bdreg = None
descreg = None
libreg = None
invreg = None
btreg = None
ssreg = None
slugreg = None

@client.command(pass_context=True)
async def namereg(ctx, *, arg):
            global namereg
            namereg = {arg}
            embed = discord.Embed(title='Registed Name.',description=f'Set the name as {arg}',colour=discord.Color.dark_green())
            print(f'{arg}')
            await ctx.send(embed = embed)

@client.command(pass_context=True)
async def add(ctx):
        role_names = [role.name for role in ctx.message.author.roles]
        if "Server Moderator" in role_names:
            def write_json(data, filename='bots.json'):
                with open (filename, "w") as f:
                    json.dump(data, f, indent=4)

            with open ('bots.json') as json_file:
                data = json.load(json_file)
                temp = data["bots"]
                y = {"name": f"{namereg}"}
                temp.append(y)

            write_json(data)
            embed = discord.Embed(title='Added!',description='Successfully added with the following!',timestamp=ctx.message.created_at,colour=discord.Color.dark_green())
            await ctx.send(embed = embed)

如果有办法没有{''},请回复此线程!谢谢你。

标签: pythonpython-3.xdiscorddiscord.py

解决方案


问题:

namereg = None

@client.command(pass_context=True)
async def namereg(ctx, *, arg):
    global namereg

这已破了。代码顶层的函数全局变量,并且在同一个命名空间中。给它一个与存储变量不同的名称。

    namereg = {arg}

这将获取来自用户输入的字符串,并创建一个包含单个元素的集合。那不是你想要的。您希望输入字符串是注册名称,所以直接分配它。

        y = {"name": f"{namereg}"}

我假设您进行了这种奇特的格式化,因为您之前遇到了错误(因为json默认情况下不会序列化集合,因为 JSON 数据格式没有直接的方式来表示它们)。您应该更仔细地聆听此错误消息,首先询问您为什么拥有无效类型的数据。输出中的{}and''来自您使用字符串格式进行字符串化的集合的字符串表示形式。您要使用的纯字符串不需要任何格式即可转换为字符串,因为它已经是字符串。


推荐阅读