0

I'm completely new to Python and even programming and also this forum. So I just was testing some new stuff that I have learned with Python like printing statements but I get this error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-2: truncated \uXXXX escape

Basically I just wrote this code:

print('C\users\desktop')

So what's going on there??

1 Answers1

0

As the error message suggests, \u is being interpreted as an escape. In Python 3, you can avoid this by using a raw string:

>>> print(r'C\users\desktop')
C\users\desktop

Unfortunately, in Python 2 \u escapes are still interpreted inside raw (unicode) strings, so you have to do something else. One possibility is to use bytestrings (i.e., not unicode). One possibility is to do 'C\\users\\desktop'. Another is to do something like 'C\\' r'users\desktop' (using string concatenation by juxtaposition). I have encountered this issue myself with Python 2 and, personally, since 99% of the problem is with the Users directory on Windows, I just created a directory junction that aliases C:\TheUsers to C:\Users. Then I can do r"C:\TheUsers" with no problems.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • in python 2, it works (\u isn't anything special).OP is probably using python 3. `>>> "c:\users" => 'c:\\users'`. using python 2.7.12 here. – Jean-François Fabre Oct 29 '17 at 20:20
  • @Jean-FrançoisFabre: `\u` is indeed a recognized escape in Python 2. See [the docs](https://docs.python.org/2/reference/lexical_analysis.html#string-literals). – BrenBarn Oct 29 '17 at 20:39
  • ok, then it doesnt work. Have you tested my example above? I know for sure that people have codes that worked with `\U` in python 2 and broke in python 3. it's in the doc, but it doesn't work. – Jean-François Fabre Oct 29 '17 at 20:43
  • @Jean-FrançoisFabre: I don't know what you're talking about. Unicode escapes work fine in Python 2. In fact they work all too well, because in the situation described in this question, there's no way to turn them off. – BrenBarn Oct 29 '17 at 20:45
  • you seem to have some bad experience about that so I believe you, but on my windows box python 2.7.12 it just has no effect, like `\c`. which version are you using? maybe they "fixed" in on newer 2.7 releases – Jean-François Fabre Oct 29 '17 at 20:48
  • @Jean-FrançoisFabre: Ah, I see the confusion. `\u` only works in *unicode* strings in Python 2. I always use `from __future__ import unicode_literals` so this didn't occur to me. – BrenBarn Oct 30 '17 at 00:17