python str.replace doesn't actually change the string
I have a question about Python and Json. I am coding a bot for discord using discord py and I wanted to have a config file. In my code, I need to replace a string from a variable located in a Python file.
This is my current code:
#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))
and
{
"nowplaying":"with buttons",
"ownerid":"173442411878416384",
"prefix":"?",
"token":"..."
}
When I enter the command:, ?prefix *newprefix*
there is no exit in the divorce or terminal, nothing changes. Can anyone show me a way to do this?
source to share
str.replace
is not an in-place operation, so you will need to assign the result back to the original variable. What for? Because the strings are immutable.
For example,
>>> string = 'testing 123'
>>> string.replace('123', '')
'testing '
>>> string
'testing 123'
You will need to assign the replaced string to your original. So change this line:
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
To that:
stringified = stringified.replace('"prefix" : prefix, "prefix" : newprefix')
source to share
In addition to @ Coldspeed's answer, which is valid, you should pay attention to the way you use the str.replace () function:
stringified.replace('"prefix" : prefix, "prefix" : newprefix')
Here you only pass one argument to replace: '"prefix" : prefix, "prefix" : newprefix'
If I understand your code correctly, you can use the following function:
stringified = stringified.replace('"prefix":"?"', '"prefix":"{}"'.format(newprefix))
This will replace the original string in your JSON. But instead of using str.replace()
which is not very flexible, it might be a good idea to use a regex to perform string replacement in all cases, even if you have spaces before and / or after the character :
.
Example:
stringified = re.sub(r'("prefix"\s?:\s?)"(\?)"', r'\1"{}"'.format(newprefix), stringified)
source to share