Struggling with replace method

I am trying to write this code to check if any of the ord values of the characters in the argument string are multiples of the number in the argument, and then remove them. For some reason it is only removing the h, even though if I ask it to print the values to be replaced it outputs b, d, and f as well. Not sure quite what is going on here.

Please don’t post screenshots.

Copy and paste any code or traceback, and in order to preserve formatting, select the code or traceback that you posted and then click the </> button.

You’re removing the character from word and putting the result in newword each time, so you’ll only ever get the result of the final replacement or an exception if no replacement occurred.


an fyi, when you’re entering code, please use the key above: </>. It tells you specifically where to enter the code.

Now, regarding your test script, is this what you want? What you have to do is use the word variable since this is what you want to update (since it has history). The way that you have it, with newword, it continually gets overwritten.

def removemult(word, num):

    for ch in word:

        if ord(ch)//num == ord(ch)/num:

            word = word.replace(ch, '')
            print(word) # For testing purposes only - remove afterwords


removemult('abcdefgh', 2)

For future reference, ord(ch)//num == ord(ch)/num is ord(ch) % num == 0 is not (ord(ch) % 0) is not ord(ch) % 0.

First, it creates a new string with the b removed, and calls it newword, while word is unchanged. Then it creates a new string with the d removed, reusing the name newword (ignoring whatever newword was before that), still not changing word. Etc. Hopefully it’s clear how this explains the behaviour you observed.

If you want to make many cumulative changes to the same variable, then each change needs to update the variable in some way (whether by making it name a new object, or by modifying the object).