简体   繁体   中英

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

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']

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM