简体   繁体   中英

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

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']

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

The translation is a function of python's syntax, so it only occurs during python's parsing of input to python itself (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM