获取字节对象中不可打印字符总数的最快方法

2024-09-29 22:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在找这样的东西:

allBytes = b'\1Hello World!\127\0'
print(countNonPrintables(allBytes))  # prints 3

您可以迭代所有字节并手动确定它们的可打印性,但这对我来说太慢了,尤其是对于字节对象>;2k字节

(慢)例如:

def countNonPrintables(allBytes: bytes) -> int:
    nonPrintablesCount = 0
    for b in allBytes:
        # DEL:
        if b == b'\127':
            nonPrintablesCount += 1
            continue
        if ord(b) < 32:
            # BS, HT, ESC, FF:
            if b not in {b'\b', b'\t', b'\033', b'\014'}:
                nonPrintablesCount += 1
    return nonPrintablesCount

Tags: 对象ingtworldif字节bytesdef
1条回答
网友
1楼 · 发布于 2024-09-29 22:32:57

我不确定您决定的内容是否可打印,但您可以使用python字符串方法isprintable

Return True if the string is printable, False otherwise. A string is printable if all of its characters are considered printable in repr() or if it is empty.

因此,您可以在每个字符上循环并调用isprintable方法

allBytes = b'\1Hello World!\127\0'
non_print_count = len([char for char in allBytes.decode() if not char.isprintable()])
print(non_print_count)

输出

2

相关问题 更多 >

    热门问题