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:)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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']
Method 2
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']
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0