cnd*_*cnd 92 python unicode python-3.x
我用过这个:
u = unicode(text, 'utf-8')
Run Code Online (Sandbox Code Playgroud)
但是在Python 3中遇到错误(或者......也许我只是忘了包含一些东西):
NameError: global name 'unicode' is not defined
Run Code Online (Sandbox Code Playgroud)
谢谢.
Joh*_*ooy 125
默认情况下,Python3中的文字字符串是unicode
假设文本是一个text对象,只需使用bytes
text.decode('utf-8')Python2相当于unicodePython3,所以你也可以写
str(text, 'utf-8')
Run Code Online (Sandbox Code Playgroud)
如果你更喜欢
所有文本都是Unicode; 但编码的Unicode表示为二进制数据
如果你想确保输出utf-8,这里是这个页面上3.0中unicode的一个例子:
b'\x80abc'.decode("utf-8", "strict")
Run Code Online (Sandbox Code Playgroud)
作为一种解决方法,我一直在使用它:
# Fix Python 2.x.
try:
UNICODE_EXISTS = bool(type(unicode))
except NameError:
unicode = lambda s: str(s)
Run Code Online (Sandbox Code Playgroud)
这就是我解决转换 \\uFE0F、\\u000A 等字符的问题的方法。还有使用 16 字节编码的表情符号。
\nexample = 'raw vegan chocolate cocoa pie w chocolate & vanilla cream\\\\uD83D\\\\uDE0D\\\\uD83D\\\\uDE0D\\\\u2764\\\\uFE0F Present Moment Caf\\\\u00E8 in St.Augustine\\\\u2764\\\\uFE0F\\\\u2764\\\\uFE0F '\nimport codecs\nnew_str = codecs.unicode_escape_decode(example)[0]\nprint(new_str)\n>>> 'raw vegan chocolate cocoa pie w chocolate & vanilla cream\\ud83d\\ude0d\\ud83d\\ude0d\xe2\x9d\xa4\xef\xb8\x8f Present Moment Caf\xc3\xa8 in St.Augustine\xe2\x9d\xa4\xef\xb8\x8f\xe2\x9d\xa4\xef\xb8\x8f '\nnew_new_str = new_str.encode('utf-16', errors='surrogatepass').decode('utf-16')\nprint(new_new_str)\n>>> 'raw vegan chocolate cocoa pie w chocolate & vanilla cream\xe2\x9d\xa4\xef\xb8\x8f Present Moment Caf\xc3\xa8 in St.Augustine\xe2\x9d\xa4\xef\xb8\x8f\xe2\x9d\xa4\xef\xb8\x8f '\nRun Code Online (Sandbox Code Playgroud)\n