Python encode list to bytes

Converting a sequence of bytes to a Unicode string is done by calling the decode() method on that str (in Python 2.x) or bytes (Python 3.x) object.

If you actually have a list of bytes, then, to get this object, you can use ''.join(bytelist) or b''.join(bytelist).

You need to specify the encoding that was used to encode the original Unicode string.

However, the term "Python string" is a bit ambiguous and also version-dependent. The Python str type stands for a byte string in Python 2.x and a Unicode string in Python 3.x. So, in Python 2, just doing ''.join(bytelist) will give you a str object.

Demo for Python 2:

In [1]: 'тест'
Out[1]: '\xd1\x82\xd0\xb5\xd1\x81\xd1\x82'

In [2]: bytelist = ['\xd1', '\x82', '\xd0', '\xb5', '\xd1', '\x81', '\xd1', '\x82']

In [3]: ''.join(bytelist).decode('utf-8')
Out[3]: u'\u0442\u0435\u0441\u0442'

In [4]: print ''.join(bytelist).decode('utf-8') # encodes to the terminal encoding
тест

In [5]: ''.join(bytelist) == 'тест'
Out[5]: True

Last update on August 19 2022 21:51:38 (UTC/GMT +8 hours)

Python Basic: Exercise-118 with Solution

Write a Python program to create a bytearray from a list.

Sample Solution:-

Python Code:

print()
nums = [10, 20, 56, 35, 17, 99]
# Create bytearray from list of integers.
values = bytearray(nums)
for x in values: print(x)
print()

Sample Output:

10                                                                                                            
20                                                                                                            
56                                                                                                            
35                                                                                                            
17                                                                                                            
99

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to prove that two string variables of same value point same memory location.
Next: Write a Python program to round a floating-point number to specified number decimal places.

Python: Tips of the Day

Function With Multiple Outputs:

If a function is required to return multiple values then:

[Variable] AggregateFunction([Value] for [item] in [collection])

In this tutorial, we will learn about the Python bytes() method with the help of examples.

The bytes() method returns an immutable bytes object initialized with the given size and data.

Example

message = 'Python is fun'

# convert string to bytes byte_message = bytes(message, 'utf-8')

print(byte_message) # Output: b'Python is fun'


bytes() Syntax

The syntax of bytes() method is:

bytes([source[, encoding[, errors]]])

bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256.

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


bytes() Parameters

bytes() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails (Read more: String encoding)

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
String Converts the string to bytes using str.encode() Must also provide encoding and optionally errors
Integer Creates an array of provided size, all initialized to null
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 Must be iterable of integers between 0 <= x < 256
No source (arguments) Creates an array of size 0


bytes() Return Value

The bytes() method returns a bytes object of the given size and initialization values.


Example 1: Convert string to bytes

string = "Python is interesting."

# string with encoding 'utf-8'

arr = bytes(string, 'utf-8')

print(arr)

Output

b'Python is interesting.'

Example 2: Create a byte of given integer size

size = 5

arr = bytes(size)

print(arr)

Output

b'\x00\x00\x00\x00\x00'

Example 3: Convert iterable list to bytes

rList = [1, 2, 3, 4, 5]

arr = bytes(rList)

print(arr)

Output

b'\x01\x02\x03\x04\x05'

What is b '\ x00 in Python?

b means bytes , not binary. \x00 is not string 0 but char with code 0 which can't be displayed so Python shows its code. – furas.

How do I turn a list into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you write bytes in Python?

Use open() and file..
bytes = b"0x410x420x43".
f = open("sample.txt", "wb").
f. write(bytes).
f. close().

What is the purpose of bytes () in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.