Python将字符串转换为字节

9

我正在尝试进行一些串行输入和输出操作,其中之一是将8x8数组发送到外部设备(Arduino)。pySerial库要求我发送的信息必须是一个字节。然而,在我的Python代码中,8x8矩阵由类型为<class 'str'>的元素组成。以下是我的发送函数:

import serial
import Matrix

width = 8
height = 8
portName = 'COM3'

def sendMatrix(matrix):
    try:
        port = serial.Serial(portName, 9600, timeout = 1000000)
        port.setDTR(0)
        print("Opened port: \"%s\"." % (portName))
        receivedByte = port.read()
        print(int(receivedByte))
        if (receivedByte == '1'):
            port.write('1')
        bytesWritten = 0
        for row in range(8):
            for col in range(8):
                value = matrix.getPoint(col, row)
                bytesWritten += port.write(value)//ERROR HERE!
        print(int(port.read()));
        port.close()
        print("Data (%d) sent to port: \"%s\"." % (bytesWritten, portName))
    except:
        print("Unable to open the port \"%s\"." % (portName))


def main():
    matrix = Matrix.Matrix.readFromFile('framefile', 8, 8)
    matrix.print()
    print(type(matrix.getPoint(0, 0)))
    print(matrix.getPoint(1, 1))
    sendMatrix(matrix)

main()

现在,我有一个类叫做 Matrix,它包含一个名为 map 的字段,这是所讨论的数组,并且我将在此处包含该代码,但是我遇到的问题是数组中的每个元素都是 str 类型,但我需要将其转换为字节。由于在实践中,我只使用0和1,因此可以忽略可能的数据损失。

我的 Matrix 类:

class Matrix(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.map = [[0 for x in range(width)] for y in range(height)]

    def setPoint(self, x, y, value):
        if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):
            self.map[y][x] = value

    def getPoint(self, x, y):
        if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):
            return self.map[y][x]

    def print(self):
        for row in range(self.height):
            for col in range(self.width):
                print(str(self.map[row][col])+" ", end="")
            print()

    def save(self, filename):
        f = open(filename, 'w')
        for row in range(self.height):
            for col in range(self.width):
                f.write(str(self.map[row][col]))
            f.write('\n')
        f.close()

    def toByteArray(self):
        matrixBytes = bytearray(self.width * self.height)
        for row in range(self.height):
            for col in range(self.width):
                matrixBytes.append(int(self.map[row][col]))
        return matrixBytes

    def getMap(self):
        return self.map

    def readFromFile(filename, width, height):
        f = open(filename, 'r')
        lines = list(f)
        matrix = Matrix(width, height)
        f.close()
        for row in range(len(lines)):
            matrix.map[row] = lines[row].strip('\n')
        return matrix

为什么不直接执行 bytes(matrix.toByteArray()) 呢? - PM 2Ring
矩阵是一个对象,它包含宽度、高度和一个二维数组。它不仅仅是一个可迭代的数据结构。 - Andrew Lalis
1
当然可以,但你的 matrix.toByteArray 方法的代码看起来将矩阵数据正确序列化为了一个字节数组,内置的 bytes 函数可以使用该字节数组生成一个 bytes 对象。 - PM 2Ring
2个回答

18

要在Python中将Unicode字符串转换为字节字符串,请执行以下操作:

>>> 'foo'.encode('utf_8')
b'foo'

将字节字符串转换为Unicode字符串:

>>> b'foo'.decode('utf_8')
'foo'

请参阅标准库中的encodedecode

可用的编码在此表格中记录。 常用的编码是utf_8utf_8_sigasciilatin_1cp1252。 请参见维基百科上的UTF-8BOMASCIILatin-1Windows-1252

有助于调试的是raw_unicode_escape。请参阅此表格


6
在Python 3.x中,您可以像下面这样使用bytesstr
>>> bytes('foo'.encode())
b'foo'

>>> a = bytes('foo'.encode())
>>> str(a.decode())
'foo'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接