python str.replace实际上并不修改字符串
我有一个关于Python和Json的问题。 我正在使用discord py为discord编写一个bot,我想要一个配置文件。在我的代码中,我需要替换Python文件中变量的字符串 这是我当前的代码:python str.replace实际上并不修改字符串,python,string,Python,String,我有一个关于Python和Json的问题。 我正在使用discord py为discord编写一个bot,我想要一个配置文件。在我的代码中,我需要替换Python文件中变量的字符串 这是我当前的代码: #change prefix @bot.command(pass_context=True) async def prefix(ctx, newprefix): with open("config.json", 'a+') as f: stringified = JSON.
#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))
以及:
当我输入命令:
?prefix*newprefix*
时,discord或终端中没有输出,没有任何更改。有人能告诉我一种方法吗?str.replace
不是就地操作,因此您需要将结果分配回原始变量
比如说,
>>> string = 'testing 123'
>>> string.replace('123', '')
'testing '
>>> string
'testing 123'
您必须将替换的字符串指定给原始字符串。因此,改变这一行:
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
为此:
stringified = stringified.replace('"prefix" : prefix, "prefix" : newprefix')
除了有效的@Coldspeed answer外,还必须注意str.replace()函数的使用方式:
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
在这里,您只传递一个参数来替换:““prefix”:prefix,“prefix”:newprefix”
如果我正确理解了您的代码,您可以使用以下功能:
stringified = stringified.replace('"prefix":"?"', '"prefix":"{}"'.format(newprefix))
这将确保替换JSON中的原始字符串。但是与其使用不太灵活的str.replace()
,不如在所有情况下使用正则表达式来执行字符串替换,即使在:
字符之前和/或之后有空格
例如:
stringified = re.sub(r'("prefix"\s?:\s?)"(\?)"', r'\1"{}"'.format(newprefix), stringified)
执行以下操作时:stringified=stringified.replace('prefix':prefix,'prefix':newprefix')stringified.replace('prefix','newprefix')仍然没有输出。是否将'prefix'替换为'newprefix'?
stringified = re.sub(r'("prefix"\s?:\s?)"(\?)"', r'\1"{}"'.format(newprefix), stringified)