incredaboy
incredaboy

Reputation: 464

python str.replace does not actually modify 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 output in discord or the terminal, nothing changes. Can anyone show me a way to do this?

Upvotes: 2

Views: 3480

Answers (2)

cs95
cs95

Reputation: 403218

str.replace is not an in-place operation, thus you will need to assign the result back to the original variable. Why? Because strings are immutable.

For example,

>>> string = 'testing 123'
>>> string.replace('123', '')
'testing '
>>> string
'testing 123' 

You'll have to assign the replaced string to your original. So change this line:

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

To this:

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

Upvotes: 3

Antwane
Antwane

Reputation: 22688

In addition to @Coldspeed answer which is valid, you must pay attention to the way you use str.replace() function:

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

Here, you pass only 1 argument to replace: '"prefix" : prefix, "prefix" : newprefix'

If I understand correctly your code, you may use the function as follow:

stringified = stringified.replace('"prefix":"?"', '"prefix":"{}"'.format(newprefix))

This will make sure the original string in your JSON will be replaced. But instead of using str.replace() which is not very flexible, maybe it's a good idea to use regular expression to perform the string replacement in all case, even if you have spaces before and/or after : character.

Example:

stringified = re.sub(r'("prefix"\s?:\s?)"(\?)"', r'\1"{}"'.format(newprefix), stringified)

Upvotes: 0

Related Questions