Skip to content
Advertisement

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:

[(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:)

Advertisement

Answer

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']
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement