Just for fun, I wrote this simple function to reverse a string in Python:
def reverseString(s):
ret = ""
for c in s:
ret = c + ret
return ret
Now, if I pass in the following two strings, I get interesting results.
print reverseString("Pla\net")
print reverseString("Plan\et")
The output of this is
te
alP
te\nalP
My question is: Why does the special character \n get translated into a new line when passed into the function, but not when the function parses it together by reversing n\? Also, how could I stop the function from parsing \n and instead return n\?
You should take a look at the individual character sequences to see what happens:
So as you can see,
\nis a single character while\eare two characters as it is not a valid escape sequence.To prevent this from happening, escape the backslash itself, or use raw strings: