Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 bytes Function

The Python bytes() function

Python3 Built-in Functions Python3 built-in function


bytes() is a built-in Python function that creates an immutable sequence of bytes.

A byte sequence (bytes) is the basic type in Python for handling binary data, commonly used in file I/O, network transfers, image processing, and similar scenarios. bytes is immutable and cannot be modified after creation.

Word meaning: bytes means "byte", the binary data type in Python.


Basic syntax and parameters

Syntax format


bytes(source)
bytes(source, encoding)
bytes(source, encoding, errors)

Parameter Description

- Type: integer, iterable, string - Description: the source data used to initialize the byte sequence. - Type: string - Description: the encoding of the string (such as 'utf-8'). - Type: string - Description: how encoding errors are handled.

Function description


Example

Example 1: creating bytes

Example

Create bytes of a specified length

b

=

bytes

(

5

)

print

(

b

)

         

Output: b'\x00\x00\x00\x00\x00'

Create from an iterable

b

=

bytes

(

[

72

,

101

,

108

,

108

,

111

]

)

print

(

b

)

         

Output: b'Hello'

Create from a string (encoding required)

b

=

bytes

(

"Hello" (Chinese)

,

encoding

=

'utf-8'

)

print

(

b

)

         

Output: b'\xe4\xbd\xa0\xe5\xa5\xbd'

Use a literal

b

=

b

"Hello"

print

(

b

)

         

Output: b'Hello'

Expected output:

b'\x00\x00\x00\x00\x00'
b'Hello'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
b'Hello'

Code analysis:

  1. bytes(5) creates 5 zero bytes.
  2. Elements of an iterable must be integers from 0 to 255.
  3. Converting a string requires specifying an encoding.

Example 2: bytes operations

Example

Access a byte

b

=

b

"Hello"

print

(

b

[

0

]

)

     

Output: 72

print

(

b

[

1

]

)

     

Output: 101

Slicing

print

(

b

[

1

:

4

]

)

   

b'ell'

Iteration

for

byte

in

b

"ABC"

:

   

print

(

byte

,

end

=

" "

)

print

(

)

 

Output: 65 66 67

Convert back to a string

b

=

b

"Hello"

s

=

b.

decode

(

'utf-8'

)

print

(

s

)

 

Output: Hello

bytes is immutable

b[0] = 65 # this raises TypeError

Expected output:

72
101
b'ell'
65 66 67
Hello

bytes supports indexing, slicing, iteration, and other operations, but its elements cannot be modified.


Python3 Built-in Functions Python3 built-in function