Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a bytearray in a tuple in a list to a string?

I am trying to fetch data from my mysql database using python:

import mysql.connector

myDB = mysql.connector.connect(
host = "<host>",
port = "<port>",
user = "<user>",
password = "<passwd>",
database = "<database>"
)

mycursor = myDB.cursor()

mycursor.execute("SELECT binaryValue FROM users")

myresult = mycursor.fetchall()

This reads a column in my database called binaryValue, where every row is either a "0" or a "1"

When I print out the variable "myresult", it gives me a list where each item is a tuple:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),)]

I need to get a string with either "0" or "1" for every item in this list

I have looked online to try and figure out how to do this, but nothing is working

Thanks in advance:)

>Solution :

You can do it with list comprehension and .decode():

a = [(bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),)]
[i[0].decode() for i in a]

Output:

['0', '0', '1', '0', '0', '1', '0', '0', '0', '1']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading