如何在Python中迭代UTF-8?

问题描述 投票:0回答:1

我如何遍历utf 8?

import string

for character in string.printable[1:]:
    print (character)

大概对于UTF-8也有类似的方法?

python encoding utf-8 character-encoding ascii
1个回答
1
投票

大概对于UTF-8也有类似的方法?

您是否想知道哪些代码点可以在ASCII范围之外打印?还是您想要可打印字符的utf8编码?

要获取所有unicode的所有可打印代码点:

unicode_max = 0x10ffff
printable_glyphs = [ chr(x) for x in range(0, unicode_max+1) if chr(x).isprintable() ]

如上所述,utf8是一种编码。那时文本被映射到特定的字节,以便其他程序可以共享数据。

内存中的文本不是utf8。每个字符/字形都有一个代码点。

转换为utf-8

import unicodedata
monkey = unicodedata.lookup('monkey')

print(f"""
    glyph: {monkey}
    codepoint: Dec: {ord(monkey)}
    codepoint: Hex:  {hex(ord(monkey))}

    utf8: { monkey.encode('utf8', errors='strict') }
    utf16: { monkey.encode('utf16', errors='strict') }
    utf32: { monkey.encode('utf32', errors='strict') }
""")

输出:

glyph: 🐒
codepoint: Dec: 128018
codepoint: Hex:  0x1f412

 utf8: b'\xf0\x9f\x90\x92'
utf16: b'\xff\xfe=\xd8\x12\xdc'
utf32: b'\xff\xfe\x00\x00\x12\xf4\x01\x00'
© www.soinside.com 2019 - 2024. All rights reserved.