python str.replace实际上并没有修改字符串

时间:2017-06-25 12:18:40

标签: python string

我对Python和Json有疑问。 我正在使用discord py为不和谐编码机器人,我想要一个配置文件。在我的代码中,我需要从位于Python文件中的变量替换字符串。

这是我目前的代码:

'fields'

#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":"..." } 时,不和弦或终端没有输出,没有任何变化。谁能告诉我一个方法呢?

2 个答案:

答案 0 :(得分:2)

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')

答案 1 :(得分:0)

除了@Coldspeed有效的答案外,你必须注意你使用str.replace()函数的方式:

'"prefix" : prefix, "prefix" : newprefix'

在这里,您只传递1个参数来替换:stringified = stringified.replace('"prefix":"?"', '"prefix":"{}"'.format(newprefix))

如果我理解您的代码,您可以使用以下功能:

str.replace()

这将确保替换JSON中的原始字符串。但是,使用不是非常灵活的:而不是使用正则表达式在所有情况下执行字符串替换都是一个好主意,即使在stringified = re.sub(r'("prefix"\s?:\s?)"(\?)"', r'\1"{}"'.format(newprefix), stringified) 字符之前和/或之后有空格也是如此。

示例:

int testscore = 76;
char grade;

if (testscore >= 90) {
    grade = 'A';
} else if (testscore >= 80) {
    grade = 'B';
} else if (testscore >= 70) {
    grade = 'C';
} else if (testscore >= 60) {
    grade = 'D';
} else {
    grade = 'F';
}