如何使用bytearray计数

时间:2012-02-09 15:57:47

标签: python-3.x

>>> help(bytearray.count)
Help on method_descriptor:

count(...)
    B.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of subsection sub in
    bytes B[start:end].  Optional arguments start and end are interpreted
    as in slice notation.

>>> b = bytearray(b'abcd')
>>> b
bytearray(b'abcd')
>>> b.count('a')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: Type str doesn't support the buffer API

问题&GT;如何对bytearray使用count?

2 个答案:

答案 0 :(得分:4)

您可以搜索字节,而不是Unicode字符串:

>>> b.count(b'a')
1

答案 1 :(得分:3)

您显然需要将另一个字节数组传递给b.count

>>> b.count(b'a')