栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Python 3中遍历Unicode字符?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Python 3中遍历Unicode字符?

在具有窄Unipre构建的Python 3.2.1上:

PythonWin 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32.Portions Copyright 1994-2008 Mark Hammond - see 'Help/about PythonWin' for further copyright information.>>> import sys>>> sys.maxunipre65535

您发现的内容(UTF-16编码):

>>> s = "abcu20acU00010302U0010fffd">>> len(s)8>>> for c in s:...     print('U+{:04X}'.format(ord(c)))...     U+0061U+0062U+0063U+20ACU+D800U+DF02U+DBFFU+DFFD

解决方法:

>>> import struct>>> s=s.enpre('utf-32-be')>>> struct.unpack('>{}L'.format(len(s)//4),s)(97, 98, 99, 8364, 66306, 1114109)>>> for i in struct.unpack('>{}L'.format(len(s)//4),s):...     print('U+{:04X}'.format(i))...     U+0061U+0062U+0063U+20ACU+10302U+10FFFD

Python 3.3更新:

现在,它可以按照OP的期望进行工作:

>>> s = "abcu20acU00010302U0010fffd">>> len(s)6>>> for c in s:...     print('U+{:04X}'.format(ord(c)))...     U+0061U+0062U+0063U+20ACU+10302U+10FFFD


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640459.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号