首页 > 解决方案 > 计算python列表中给出错误答案的字符数

问题描述

我想计算以下列表中的数字字符,但它给出的答案不正确。这不适用于此特定列表。

words = [b'#Repost@motivated.mindset\n\xe3\x83\xbb\xe3\x83\xbb\xe3\x83\xbb\'']
sum1=sum(len(i) for i in words)
print(sum1)

输出为 37

但正确答案是 68

我究竟做错了什么?

标签: python-3.xlist

解决方案


你有一个字节对象,可能是一个 utf-8 编码的字符串,你可以计算很多东西: len(word) 只是给出了这个数组中的字节数。

但是要写入使用不同符号的字节,ascii 计数一个,转义时计数两个,十六进制表示法计数 4 个字符。好像是一个utf-8编码的字符串,一个字母多一个字节,所以告诉我你要数什么。

word = b'#Repost@motivated.mindset\n\xe3\x83\xbb\xe3\x83\xbb\xe3\x83\xbb\''
index = 0
codechars = 0
for number in word:
    index+=1
    b =  number.to_bytes(1, byteorder='big')
    bs = len(str(b)[2:-1]) #b'' 
    codechars+=bs
    print("%2.0f" % index, repr(b).ljust(10-len(b)), len(b), bs, hex(number), number )

print("Byte count", index )

print(word)
print("code count", codechars )

print(word.decode("utf-8"))
print("utf-8 count", len(word.decode("utf-8")))

assert codechars==len(repr(word[2:-1]))
assert len(word)==index

输出:

...
25 b't'      1 1 0x74 116
26 b'\n'     1 2 0xa 10
27 b'\xe3'   1 4 0xe3 227
28 b'\x83'   1 4 0x83 131
29 b'\xbb'   1 4 0xbb 187
30 b'\xe3'   1 4 0xe3 227
31 b'\x83'   1 4 0x83 131
32 b'\xbb'   1 4 0xbb 187
33 b'\xe3'   1 4 0xe3 227
34 b'\x83'   1 4 0x83 131
35 b'\xbb'   1 4 0xbb 187
36 b"'"      1 1 0x27 39
Byte count 36
b"#Repost@motivated.mindset\n\xe3\x83\xbb\xe3\x83\xbb\xe3\x83\xbb'"
code count 64
#Repost@motivated.mindset
・・・'
utf-8 count 30

推荐阅读