python3输出unicode

本文介绍了Python 2.x和3.x中ord()和chr()函数在处理Unicode字符上的区别。在Python 2.x中,ord()函数用于获取字符的Unicode编码,而chr()函数用于从编码值创建字符,但对于大于255的Unicode值,chr()会引发错误。在Python 3.x中,这两个函数已能正确处理Unicode字符串。

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

采用ord函数即可

In Python 2.x

Python代码  收藏代码
  1. D:\Python27>python  
  2.   
  3. >>> chr(65)  
  4. 'A'  
  5.   
  6. >>> ord('A')  
  7. 65  
  8.   
  9. >>> unichr(20013)  
  10. u'\u4e2d'  
  11.   
  12. >>> ord(u'\u4e2d')  
  13. 20013  
  14.   
  15. >>> ord('中')  
  16. Traceback (most recent call last):  
  17.   File "<stdin>", line 1in <module>  
  18. TypeError: ord() expected a character, but string of length 2 found  
  19.   
  20. >>> chr(20013)  
  21. Traceback (most recent call last):  
  22.   File "<stdin>", line 1in <module>  
  23. ValueError: chr() arg not in range(256)  

 In Python  3.x

Python代码  收藏代码
  1. D:\CODE\PYTHON\OPEN_JUDGE>python  
  2. Python 3.2.5 (default, May 15 201323:06:03) [MSC v.1500 32 bit (Intel)] on win32  
  3. Type "help""copyright""credits" or "license" for more information.  
  4.   
  5. >>> chr(65)  
  6. 'A'  
  7.   
  8. >>> ord('A')  
  9. 65  
  10.   
  11. >>> chr(20013)  
  12. '中'  
  13.   
  14. >>> ord('中')  
  15. 20013  
  16.   
  17. >>> ord('\u4e2d')  
  18. 20013  

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值