在python中的bytes()调用中用方括号括起一个整数是什么意思?
假设你写bytes(10),根据我的理解,这将创建一个 10 个字节的字节数组;但是,如果您改为写入bytes([10]),则会得到二进制值 10。
方括号对数字的数据类型有什么影响?作为操作员,我找不到有关它们的任何信息。
回答
[10]是一个列表文字。它创建一个包含单个元素的列表,该元素为 10。
bytes()根据参数的不同以几种不同的方式表现,正如您从其help()文档中看到的那样:
class bytes(object)
| bytes(iterable_of_ints) -> bytes
| bytes(string, encoding[, errors]) -> bytes
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
在这种情况下,尽管仅表示一个字节,但[10]用于调用bytes(iterable_of_ints)行为而不是bytes(int)行为。