Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将包含字符的列表转换为字符串(Python)_Python_String_List_Spi - Fatal编程技术网

将包含字符的列表转换为字符串(Python)

将包含字符的列表转换为字符串(Python),python,string,list,spi,Python,String,List,Spi,我试图通过树莓皮上的SPI端口读取刺痛。这是我测试端口的代码: raw = 0 string = "" SPI = spidev.SpiDev() SPI.open(0,0) while True: raw = SPI.xfer2([0]) string += str(chr(raw)) print string print raw time.sleep(0.2) 结果是“Hellinsert-gibberish”,因此在第四个字符之后失败。我尝试发

我试图通过树莓皮上的SPI端口读取刺痛。这是我测试端口的代码:

raw = 0
string = ""

SPI = spidev.SpiDev()
SPI.open(0,0)

while True:
    raw = SPI.xfer2([0])
    string += str(chr(raw))
    print string
    print raw
    time.sleep(0.2)
结果是“Hellinsert-gibberish”,因此在第四个字符之后失败。我尝试发送“Hello World!”我发送的数据格式为列表中的字符,例如“Hello”看起来像[72、101、108、108、111]。如何将其转换为字符串


答案很有用,因为我不知道如何转换数据。然而,真正的问题是与我接口的设备。答案对发现真正的问题很有用,非常感谢!我对python还是相当陌生,所以这些东西很难理解。

如果我理解正确,您想将[72、101、108、108、111]转换为“Hello”吗

data = [72, 101, 108, 108, 111]
string = "".join([chr(n) for n in data])
print string
输出:

Hello
您可以使用或配合:


还可以考虑将转换后的字符追加到字符串,如下所示

str = ""
for c in [chr(n) for n in lst]:
    str += c
更新

在函数式编程风格中,如下所示

from functools import reduce
reduce( (lambda x,y: x + chr(y)), [72, 101, 108, 108, 111], "")
其中
reduce
将lambda函数应用于列表中的每个项目,从空字符串(最后一个参数)开始。lambda函数可以这样定义

def append(str,n): return str + chr(n)
因此对
reduce
的调用变得不那么冗长

reduce( append, [72, 101, 108, 108, 111], "")
'Hello'

谢谢,这就是我需要读的未知长度的字符串!伟大的
reduce( append, [72, 101, 108, 108, 111], "")
'Hello'