Jim
Jim

Reputation: 4669

How is this weird behaviour of escaping special characters explained?

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\?

Upvotes: 0

Views: 122

Answers (3)

poke
poke

Reputation: 387745

You should take a look at the individual character sequences to see what happens:

>>> list("Pla\net")
['P', 'l', 'a', '\n', 'e', 't']
>>> list("Plan\et")
['P', 'l', 'a', 'n', '\\', 'e', 't']

So as you can see, \n is a single character while \e are two characters as it is not a valid escape sequence.

To prevent this from happening, escape the backslash itself, or use raw strings:

>>> list("Pla\\net")
['P', 'l', 'a', '\\', 'n', 'e', 't']
>>> list(r"Pla\net")
['P', 'l', 'a', '\\', 'n', 'e', 't']

Upvotes: 4

Marcin
Marcin

Reputation: 49846

The translation is a function of python's syntax, so it only occurs during python's parsing of input to python itself (i.e. when python parses code). It doesn't occur at other times.

In the case of your programme, you have a string which by the time it is constructed as an object, contains the single character denoted by '\n', and a string which when constructed contains the sub-string '\e'. After you reverse them, python doesn't reparse them.

Upvotes: 1

Bwmat
Bwmat

Reputation: 4578

The reason is that '\n' is a single character in the string. I'm guessing \e isn't a valid escape, so it's treated as two characters.

look into raw strings for what you want, or just use '\\' wherever you actually want a literal '\'

Upvotes: 2

Related Questions