Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bytearray to bytes-like object?

In Python 3 I'm getting error TypeError: a bytes-like object is required, not 'bytearray'

I have a bytearray, which looks like this:

 >>> print(my_ba)
 bytearray(b'}\x0e\x15/ow4|-')

If I enter this in the console it works:

 >>> print(base58.b58encode(b'}\x0e\x15/ow4|-'))
 2bKmhuGiGP7t8

But this gives an error, and I can't find out how to get the b'' string from the bytearray:

 >>> print(base58.b58encode(my_ba))
 TypeError: a bytes-like object is required, not 'bytearray'

I'm sure it's obvious, but how do I convert the bytearray to a string with a b prefix?

like image 815
Keir Finlow-Bates Avatar asked Sep 05 '17 22:09

Keir Finlow-Bates


People also ask

How do you decode Bytearray in Python?

Using the decode() Function to convert Bytearray to String in Python. An alternative way to convert a bytearray to string is by using the decode() method. The decode() method, when invoked on a bytearray object, takes the encoding format as input and returns the output string.

What is the difference between bytes and Bytearray?

The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.

How do you use bytes and Bytearray in Python?

Python | bytearray() functionbytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways.


1 Answers

As Coldspeed put it in the comments, just pass a bytearray to a bytes call:

bytes(my_ba)

like image 122
jsbueno Avatar answered Nov 02 '22 20:11

jsbueno