Emoji 的 Python unicode 字符转换

标签 python string unicode formatting emoji

我在将字节有序标记格式化为 unicode 时遇到了一些问题。我的角色的表达方式有些奇怪。基本上它不是在 Python 中打印表情符号字符,而只是字符串。这是我的例子。

# these codes are coming from a json file; this a representation of one of the codes.
e = 'U+1F600' # smile grin emoji

# not sure how to clean this, so here's a basic attempt using regex.
b = re.compile(r'U\+', re.DOTALL).sub('\U000', e)

print unicode(b) # output should be '\U0001F600'

无论出于何种原因,这都不会打印表情符号字符。

但是,如果您输入与文字相同的字符串,使用 u 标志,一切都会按预期工作。

print u'\U0001F600'

我在这里做错了什么?我认为 unicode 函数会将我的字符串转换为有效的等效字符串,但显然不是。

我正在使用 Python 2.7

最佳答案

我想 decode 就是你要找的,

>>> b = '\U0001F600'
>>> print b.decode('unicode-escape')
😀

>>> print unicode(b, 'unicode-escape')
😀

问题

print unicode(b)

unicode 函数尝试将字符串 \U0001F600 转换为 unicode,结果是 \\U0001F600。为防止这种情况,我们将当前编码提供为 unicode-escape

关于Emoji 的 Python unicode 字符转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604811/

相关文章:

python - 显示从文件中读取的 unicode

python - 打印输出未显示正确的格式

javascript - 如何使用递归遍历嵌套数组?

java - 如何比较Java中的字符串?

c++ - GetWindowText 无法处理商标符号

python - OpenCv - cv2.VideoWriter对象没有属性释放

c - 如何获取多字节字符串的字节大小

java - 如何在Java中每第n次出现字符时分割字符串

python - 解码文件名问题

python - 如何使用 boost.python 提取 unicode 字符串