String replace doesn’t appear to be working

Strings in Python are immutable. That means that a given string object will never have its value changed after it has been created. This is why an element assignment like some_str[4] = "x" will raise an exception.

For a similar reason, none of the methods provided by the str class can mutate the string. So, the str.replace method does not work the way I think you expect it to. Rather than modifying the string in place, it returns a new string with the requested replacements.

Try:

encrypted_str = encrypted_str.replace(encrypted_str[j], dec_str2[k], 2)

If you’re going to be making many such replacements, it may make sense to turn your string into a list of characters, make the modifications one by one, then use str.join to turn the list back into a string again when you’re done.

Leave a Comment