Python中字符、汉字、数字转为Unicode码

本文介绍了如何在Python中实现字符与Unicode之间的转换,包括英文字符、汉字以及其他特殊符号,并提供了一个具体的实例来演示这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载地址: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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值