在python中将十六进制字符转换为Unicode字符 [英] Convert from hex character to Unicode character in python

查看:1438
本文介绍了在python中将十六进制字符转换为Unicode字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

十六进制字符串'\xd3'也可以表示为:Ó

最简单的方法是将十六进制字符串的字符表示形式呈现给控制台:

  print unichr(ord('\xd3'))

或者用英文,将十六进制字符串转换为数字,然后将该数字转换为一个unicode代码点,然后将其输出到屏幕。这似乎是一个额外的步骤。有没有更简单的方法?

解决方案

  print u'\xd3'

是你所要做的。你只需要以某种方式告诉Python它是一个unicode文字;领先的 u 就是这样做的。它甚至可以用于多个字符。



如果你不是在谈论文字,而是一个变量:

  codepoints ='\xd3\xd3'
打印codepoints.decode(latin-1)

编辑:如果 print ing与您的终端编码不兼容,则指定特定编码将不起作用,自动 print do 编码(sys.stdout.encoding)。谢谢@ThomasK。


The hex string '\xd3' can also be represented as: Ó.

The easiest way I've found to get the character representation of the hex string to the console is:

print unichr(ord('\xd3'))

Or in English, convert the hex string to a number, then convert that number to a unicode code point, then finally output that to the screen. This seems like an extra step. Is there an easier way?

解决方案

print u'\xd3'

Is all you have to do. You just need to somehow tell Python it's a unicode literal; the leading u does that. It will even work for multiple characters.

If you aren't talking about a literal, but a variable:

codepoints = '\xd3\xd3'
print codepoints.decode("latin-1")

Edit: Specifying a specific encoding when printing will not work if it's incompatible with your terminal encoding, so just let print do encode(sys.stdout.encoding) automatically. Thanks @ThomasK.

这篇关于在python中将十六进制字符转换为Unicode字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆