如何删除变量中的{'}?

2024-10-02 20:34:58 发布

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

我最近发出了一个命令,将信息保存到JSON文件中。基本上,我有两个命令,第一个命令设置全局变量,第二个命令使用提供的变量添加到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)

如果有办法不使用{“”},请回复此线程!多谢各位


Tags: 文件name命令nonejsondatadefas
2条回答

如果将其写入JSON文件,则每次都会添加引号作为JSON语法的一部分。如果您只需要将字典写入一个文件(该文件也是可读的),您可以将其写入一个普通的.txt文件

问题:

namereg = None

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

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

    namereg = {arg}

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

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

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

相关问题 更多 >