Unicode literals causing invalid syntax

风流意气都作罢 提交于 2019-12-20 01:45:38

问题


The following code:

s = s.replace(u"&", u"&")

is causing an error in python:

SyntaxError: invalid syntax

removing the u's before the " fixes the problem, but this should work as is? I'm using Python 3.1


回答1:


The u is no longer used in Python 3. String literals are unicode by default. See What's New in Python 3.0.

You can no longer use u"..." literals for Unicode text. However, you must use b"..." literals for binary data.




回答2:


On Python 3, strings are unicode. There is no need to (and as you've discovered, you can't) put a u before the string literal to designate unicode.

Instead, you have to put a b before a byte literal to designate that it isn't unicode.




回答3:


In Python3.3+ unicode literal is valid again, see What’s New In Python 3.3:

New syntax features:

New yield from expression for generator delegation.
The u'unicode' syntax is accepted again for str objects.



来源:https://stackoverflow.com/questions/7569014/unicode-literals-causing-invalid-syntax

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