【问题标题】:python str.replace does not actually modify the stringpython str.replace 实际上并没有修改字符串
【发布时间】:2017-06-25 12:18:39
【问题描述】:

我有一个关于 Python 和 Json 的问题。 我正在使用 discord py 编写一个不和谐的机器人,我想要一个配置文件。在我的代码中,我需要从位于 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 或终端没有输出,没有任何变化。谁能告诉我一个方法来做到这一点?

【问题讨论】:

  • 你想用'newprefix'替换'prefix'吗?

标签: python string


【解决方案1】:

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

【讨论】:

  • 当我这样做时: stringified = stringified.replace('"prefix" : prefix, "prefix" : newprefix') stringified.replace('prefix', 'newprefix') 仍然没有输出。
【解决方案2】:

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

stringified.replace('"prefix" : prefix, "prefix" : newprefix')

在这里,您只传递了 1 个要替换的参数:'"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)

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2021-06-28
    • 2014-04-06
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多