我有一个关于Python和Json的问题。 我正在用discordpy编写一个机器人程序,我想有一个配置文件。在我的代码中,我需要替换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))
以及:
^{pr2}$当我输入命令:?prefix *newprefix*
时,在discord或终端中没有输出,没有任何更改。有人能告诉我怎么做吗?在
str.replace
不是就地操作,因此需要将结果分配回原始变量。Why? Because strings are immutable.例如
您必须将替换的字符串指定给原始字符串。所以改变这一行:
^{pr2}$为此:
除了@Coldspeed答案是有效的,你必须注意你使用的方式结构更换()功能:
这里,只传递一个参数来替换:
'"prefix" : prefix, "prefix" : newprefix'
如果我正确理解您的代码,您可以使用以下函数:
^{pr2}$这将确保JSON中的原始字符串将被替换。但是,与其使用不太灵活的
str.replace()
,不如使用正则表达式在所有情况下执行字符串替换,即使在:
字符之前和/或之后有空格。在示例:
相关问题 更多 >
编程相关推荐