如何用python3制作unicode字符串

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)

如果你更喜欢

  • TypeError:不支持解码str (51认同)
  • @Gank,在Python3中,`str`是unicode,即.它被"解码",所以在它上面调用`decode`是没有意义的 (8认同)
  • 原始样本不清楚.所以在python3中,如果你想做`str(text,'utf-8')`,文本必须是字符串二进制文件.例如`str(b'this是二进制','utf-8')` (3认同)

Tre*_*ors 9

Python 3.0中的新功能是:

所有文本都是Unicode; 但编码的Unicode表示为二进制数据

如果你想确保输出utf-8,这里是这个页面上3.0中unicode的一个例子:

b'\x80abc'.decode("utf-8", "strict")
Run Code Online (Sandbox Code Playgroud)


mag*_*rth 9

作为一种解决方法,我一直在使用它:

# Fix Python 2.x.
try:
    UNICODE_EXISTS = bool(type(unicode))
except NameError:
    unicode = lambda s: str(s)
Run Code Online (Sandbox Code Playgroud)

  • 你为什么使用lambda函数?在任何情况下,这些方法都以相同的方式调用.这是一个更简单的变化:`try:unicode = str; 除了:传递. (11认同)

Ily*_*yas 5

这就是我解决转换 \\uFE0F、\\u000A 等字符的问题的方法。还有使用 16 字节编码的表情符号。

\n
example = '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 '\n
Run Code Online (Sandbox Code Playgroud)\n