Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a Python string in a for loop?

I am building a Discord bot using the discord.py library. The library uses the on_message(ctx) event to let us modify a message if we want to. What I would like to do is to remove the formatting and replace the user mentions with the Discord names. The text of the message looks like this:

<@!34565734654367046435>  <@!34565734645354367046435> are you here?

In the ctx variable I can get the mentions as User objects from ctx.mentions and I can get the NAME and the ID of each mentioned user.

I’d like to replace the <@!34565734654367046435> with the name of the user. The result to be something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name1 Name2 are you here?

This is what I have so far but it does not seem to work.

remove_formatting = utils.remove_markdown(context.content)
print(remove_formatting) # prints the very first code styled line in this question
for member in context.mentions:
   remove_formatting.replace(f'<@!{member.id}>', member.name)

If I print the member.id and the member.name without doing anything else, I get the expected values. How do I update the string in this for loop?

>Solution :

The replace function returns a new string, it doesn’t edit the existing string in place. If you edit your loop to:

remove_formatting = utils.remove_markdown(context.content)
for member in context.mentions:
   remove_formatting = remove_formatting.replace(f'<@!{member.id}>', member.name)

it should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading