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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With