DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

2 1

Python bytes()

ItsMyCode |

Python bytes() function return an immutable byte-represented object of given size and data.

The bytes() method provides immutable (cannot be changed) sequence of objects in the range of 0 <= x < 256

If you want a mutable version, you can use the bytearray() method.

bytes() Syntax

The syntax of the bytes() method is:

**bytes([source[, encoding[, errors]]])**
Enter fullscreen mode Exit fullscreen mode

bytes() Parameters

The bytes() method takes three optional parameters.

  • source (Optional) – Initializes the array of bytes
  • encoding (Optional) – in case if the source is a string, the encoding of the string.
  • errors (Optional) – An action to take if the encoding conversion fails.

The source parameter can be of any below type as follows.

Type Description
String Converts the given string into bytes using str.encode(). In the case of a string, you must also pass encoding as an argument and, optionally errors
Integer Creates an array of provided size and initializes with null bytes
Object A read-only buffer of the object will be used to initialize the byte array
Iterable Creates an array of size equal to the iterable count and initialized to the iterable elements. The iterable should be of integers and the range should be in between 0 <= x < 256
No source (arguments) An array of size 0 is created.

bytes() Return Value

The bytes() function returns an array of bytes of the given size and initializes values.

Example 1: Create a byte of a given integer size

In the case of an integer, it creates an array of provided size and initializes with null bytes.

# size of array
size = 6

# bytes() will create an array of given size
# and initialize with null bytes
arr = bytes(size)

print(arr)
Enter fullscreen mode Exit fullscreen mode

Output

b'\x00\x00\x00\x00\x00\x00'
Enter fullscreen mode Exit fullscreen mode

Example 2: Convert string to bytes

Converts the given string into bytes using str.encode(). In the case of a string, you must also pass encoding as an argument and, optionally, errors.

# string declaration
string = "Hello World !!!"

# string with encoding 'utf-8'
arr1 = bytes(string, 'utf-8')
print(arr1)

# string with encoding 'utf-16'
arr2 = bytes(string, 'utf-16')
print(arr2)

Enter fullscreen mode Exit fullscreen mode

Output

b'Hello World !!!'
b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00 \x00!\x00!\x00!\x00'
Enter fullscreen mode Exit fullscreen mode

The string handling error is defined as:

*String Error Handlers : *

  • strict: ** Raises the default **UnicodeDecodeError in case of encoding failure.
  • *ignore: * Ignores the unencodable character and encodes the remaining string.
  • *replace: * Replaces the unencodable character with a ‘?’.

If you notice the strict type will raise an UnicodeEncodeError if the encoding fails as shown below.


from typing import Text

text = 'HellÖ WÖrld'
# Giving ascii encoding and ignore error
print("Byte conversion with ignore error : " +
      str(bytes(text, 'ascii', errors='ignore')))

# Giving ascii encoding and replace error
print("Byte conversion with replace error : " +
      str(bytes(text, 'ascii', errors='replace')))

# Giving ascii encoding and strict error throws exception
print("Byte conversion with strict error : " +
      str(bytes(text, 'ascii', errors='strict')))

Enter fullscreen mode Exit fullscreen mode


python

Output

Byte conversion with ignore error : b'Hell Wrld'
Byte conversion with replace error : b'Hell? W?rld'

Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 17, in <module>
    str(bytes(text, 'ascii', errors='strict')))
UnicodeEncodeError: 'ascii' codec can't encode character '\xd6' in position 4: ordinal not in range(128)
Enter fullscreen mode Exit fullscreen mode

Example 3: Convert iterable list to bytes

Creates an array of size equal to the iterable count and initialized to the iterable elements. The iterable should be of integers, and the range should be in between 0 <= x < 256

# list of integers
lst = [1, 2, 3, 4, 5]

# iterable as source
arr = bytes(lst)

print(arr)
print("Count of bytes:", len(arr))

Enter fullscreen mode Exit fullscreen mode

Output

b'\x01\x02\x03\x04\x05'
Count of bytes: 5
Enter fullscreen mode Exit fullscreen mode

Example 4: If no source is passed to bytes()

If no source is passed into bytes(), an array of size 0 is created.

# array of size 0 will be created

# iterable as source
arr = bytes()

print(arr)

Enter fullscreen mode Exit fullscreen mode

Output

b''
Enter fullscreen mode Exit fullscreen mode

The post Python bytes() appeared first on ItsMyCode.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Jetbrains Survey

Take part in the Developer Ecosystem Survey!

Share your thoughts and get the chance to win a MacBook Pro, an iPhone 16 Pro, or other exciting prizes. Help shape the coding landscape and earn rewards for your contributions!

Take the survey

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️