Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
ekrah Avatar asked Jan 11 '23 20:01

ekrah


2 Answers

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
like image 148
Aswin Murugesh Avatar answered Jan 29 '23 18:01

Aswin Murugesh


You were returning the original string, try

def ROT(string):
#   y = 0
    result = ""
    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))
            result = result + char
            print(char)
            continue
#           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)
            result = result + char
            continue
#           y+=1
        result = result + char
    return result

string = ROT('Hello, lorem ipsum dolor sit amet')
print(string)
like image 26
JoeC Avatar answered Jan 29 '23 19:01

JoeC