2

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?

1
  • Do you want to replace 'prefix' with 'newprefix'? Commented Jun 25, 2017 at 17:50

2 Answers 2

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

When I do: stringified = stringified.replace('"prefix" : prefix, "prefix" : newprefix') stringified.replace('prefix', 'newprefix') There is still no output.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.