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:)
CodePudding user response:
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']
CodePudding user response:
You can convert from bytearray to binary value with int
function:
result = [(bytearray(b'0'),), (bytearray(b'0'),), (bytearray(b'1'),)]
out = []
for i in result:
out.append(str(int(i[0], 2)))
print(out)
Output:
['0', '0', '1']