Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Numbers change when included in a directory string

I have searched online and can't seem to find any other instances of this. Why does 2015 become x815 and how do I remedy this?

>>> 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'
like image 901
Jack Sellers Avatar asked Jul 08 '26 07:07

Jack Sellers


2 Answers

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

As it happens, the "\" followed by three digits indicates a three digit octal character. "\201" happens to correspond the the octal character �, which, to a terminal that can't print it, may come out as the hexadecimal number x81.

To avoid this, make your string a raw string by putting the letter r in front, outside the quotes, like this

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

The r will make Python interpret the string exactly as you entered it, ignoring all special characters and escape sequences, and you will get the result you want.

like image 149
clj Avatar answered Jul 14 '26 08:07

clj


Actually \x is the escape sequence that means the next two characters are interpreted as hex digits.

So you will have :

>>> '\2015'
'\x815'

And for get ride of that you need to escape \ :

>>> print '\\2015'
\2015
like image 37
Mazdak Avatar answered Jul 14 '26 06:07

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!