我有一个关于 Python 和 Json 的问题。 我正在使用 discord py 为 discord 编写一个机器人,我想要一个配置文件。在我的代码中,我需要从位于 Python 文件中的变量中替换字符串。
这是我当前的代码:
#change prefix
@bot.command(pass_context=True)
async def prefix(ctx, newprefix):
with open("config.json", 'a+') as f:
stringified = JSON.stringify(json)
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
await ctx.send("Prefix set to: `{}`. New prefix will be applied after restart.".format(newprefix))
author = ctx.message.author
print(author, "has changed the prefix to: {}".format(newprefix))
和:
{
"nowplaying":"with buttons",
"ownerid":"173442411878416384",
"prefix":"?",
"token":"..."
}
当我输入命令:?prefix *newprefix* 时,discord 或终端中没有任何输出,没有任何变化。谁能告诉我如何做到这一点?
请您参考如下方法:
str.replace 不是就地操作,因此您需要将结果分配回原始变量。 Why? Because strings are immutable.
例如,
>>> string = 'testing 123'
>>> string.replace('123', '')
'testing '
>>> string
'testing 123'
您必须将替换后的字符串分配给您的原始字符串。所以改变这一行:
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
对此:
stringified = stringified.replace('"prefix" : prefix, "prefix" : newprefix')
