Python - numbers change when included in a directory string

I've searched online and can't seem to find any other examples of this. Why is 2015 becoming x815 and how can I fix it?

>>> os.chdir("N:\PRTR\Weekly Estimate\2015")

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    os.chdir("N:\PRTR\Weekly Estimate\2015")
WindowsError: [Error 2] The system cannot find the file specified: 'N:\\PRTR\\Weekly Estimate\x815'

      

+3


source to share


2 answers


It \x

is actually an escape sequence, which means that the next two characters are interpreted as hexadecimal digits.

So, you will have:

>>> '\2015'
'\x815'

      



And in order to deal with this, you need to run \

:

>>> print '\\2015'
\2015

      

+3


source


Actually, in Python, "\" is an escape character in strings, and all special characters are created with "\" followed by one or more other specific characters. For example, "\n"

in a string, this is a new string character.

As it happens, "\" followed by three numbers denotes an eight-digit octal character. "\201"

matches the eighth character, which may appear as a hexadecimal number to a terminal that cannot print it x81

.

To avoid this, make your string a raw string by putting the letter r

in front, outside the quotes, for example



print r'N:\PRTR\Weekly Estimate\2105'

      

r

will force Python to interpret the string exactly as you typed it, ignoring all special characters and escape sequences, and you will get the desired result.

+4


source







All Articles