Search code examples
pythonstringrot13

Why do I have to create an empty string to replace all the characters in a string?


I'm writing a ROT13 function, and I can't understand why the following doesn't work:

def ROT(string):
    # y = 0
    for char in string:
        x = ord(char)
        if 97 <= x < 110 or 65 <= x < 78:
            # string[y]=char.replace(char, chr(x+13))
            char=char.replace(char, chr(x+13))
            print(char)
            # y+=1
        elif x >= 110 or 78 <= x < 91:
            # string[y]=char.replace(char, chr(x-13))
            char=char.replace(char, chr(x-13))
            print(char)
            # y+=1
    return string

string = ROT('Hello, lorem ipsum dolor sit amet')
print(string)

The call to the function just prints the original string. As you can see in the commented lines above (apologies if it's a little hard to read), I tried defining a variable y to increment through the string, and then access it but I get a runtime error. The solution I came up with was to create an empty string at the beginning of the function (and from my googling that seems to be the solution most people use), but no one explains why that is. Why doesn't it work to return the original string if you're replacing every character in it?


Solution

  • The problem in your code is you are not manipulating the original string. You are just replacing the temporary variable char and not in the original string. Since strings are immutable in python, you may try using a new string and instead of replacing the original string, you may just append the characters to the new string. Like:

    modified_string = ""
    for char in string:
         #whatever condition
         modified_string += #value to be added