转载地址:https://blog.youkuaiyun.com/bit_sky/article/details/50926103
一、数字、字符(英文字符、标点、特殊符号等)转为Unicode码
def charToUnic(ch):
tmp_ch = hex(ord(ch))[2:]
return "0" * (4 - len(tmp_ch)) + tmp_ch
二、汉字转为Unicode码
def chineseToUnic(ch):
return ch.decode('utf-8').encode('unicode_escape')[2:]
三、Unicode码解码为汉字
str1 = '\u4f60\u597d'
print str1.decode('unicode_escape')
你好
四、实例
#!/usr/bin/python2.7
# -*- coding: utf-8 -*
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# \u59ae\u8428\u53e4\u4e3d\u0020\u0020\u827e\u5219\u5b5c
stre = u'\u59ae\u8428\u53e4\u4e3d\x07\u827e\u5219\u5b5c'
def unicode_check(stre):
if stre is None or len(stre) == 0:
return ''
else:
unicode_str = stre.decode('utf-8').encode('unicode_escape') #汉字转为unicode
# print unicode_str
temp_str = []
last_str = []
for i in unicode_str:
temp_str.append(i)
j = 0
while(j<len(temp_str)):
if (temp_str[j] == '\\' and temp_str[j+1] == 'x'):
temp_str[j+1] = 'u'
temp_str[j+2] = '0'
temp_str[j+3] = '0'
#赋值
last_str.append(temp_str[j])
last_str.append(temp_str[j+1])
last_str.append(temp_str[j+2])
last_str.append(temp_str[j+3])
last_str.append('2')
last_str.append('0')
j = j + 3 #往后 移动到了第三位
else:
last_str.append(temp_str[j])
j = j + 1
laststring = '' #保存最终的字符
for i in last_str:
laststring = laststring + i
return laststring.decode('unicode_escape') # unicode转为汉字
# a = '\xb3\xc2\xbd\xa8\xc3\xf4'
# a = '\x07'
# b = a.decode('gbk')
# print b
print unicode_check(stre)