(unicode error) 'unicodeescape' codec can't decode bytes - string with '\\u'

 ̄綄美尐妖づ 提交于 2019-11-30 10:55:22

AFAIK, all that from __future__ import unicode_literals does is to make all string literals of unicode type, instead of string type. That is:

>>> type('')
<type 'str'>
>>> from __future__ import unicode_literals
>>> type('')
<type 'unicode'>

But str and unicode are still different types, and they behave just like before.

>>> type(str(''))
<type 'str'>

Always, is of str type.

About your r'\u' issue, it is by design, as it is equivalent to ru'\u' without unicode_literals. From the docs:

When an 'r' or 'R' prefix is used in conjunction with a 'u' or 'U' prefix, then the \uXXXX and \UXXXXXXXX escape sequences are processed while all other backslashes are left in the string.

Probably from the way the lexical analyzer worked in the python2 series. In python3 it works as you (and I) would expect.

You can type the backslash twice, and then the \u will not be interpreted, but you'll get two backslashes!

Backslashes can be escaped with a preceding backslash; however, both remain in the string

>>> ur'\\u'
u'\\\\u'

So IMHO, you have two simple options:

  • Do not use raw strings, and escape your backslashes (compatible with python3):

    'H:\\unittests'

  • Be too smart and take advantage of unicode codepoints (not compatible with python3):

    r'H:\u005cunittests'

For me this issue related to version not up to date, in this case numpy

To fix :

conda install -f numpy

I try this on Python 3:

import os

os.path.abspath("yourPath")

and it's worked!

When you're writing string literals which contain backslashes, such as paths (on Windows) or regexes, use raw strings. That's what they're for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!