要使用python字符串的ascii序号列表
我有一个ascii序号列表,如:要使用python字符串的ascii序号列表,python,string,list,Python,String,List,我有一个ascii序号列表,如: [102, 114, 97, 110, 99, 101, 115, 99, 111, 0, 0, 0, 0, 0, 0, 0] 现在我想把它转换成一个字符串,去掉结尾的空字符 我试过了 contenuto_tag = "".join(map(chr, backdata)) 但是当我把它传递给一个函数,比如: enos.system("php ../trigger_RFID.php %s"%(contenuto_tag)) 我有一个错误: TypeErro
[102, 114, 97, 110, 99, 101, 115, 99, 111, 0, 0, 0, 0, 0, 0, 0]
现在我想把它转换成一个字符串,去掉结尾的空字符
我试过了
contenuto_tag = "".join(map(chr, backdata))
但是当我把它传递给一个函数,比如:
enos.system("php ../trigger_RFID.php %s"%(contenuto_tag))
我有一个错误:
TypeError: must be string without null bytes, not str
可能是因为结尾有空字符。使用理解,只在非0上执行
chr
:
a = [102, 114, 97, 110, 99, 101, 115, 99, 111, 0, 0, 0, 0, 0, 0, 0]
b = ''.join(chr(i) for i in a if i)
print(b) # outputs francesco
首先过滤掉空字节(Python 2版本): 替代方法:
>>> ''.join(map(chr, filter(None, a)))
'francesco'
一些时间安排:
In [13]: a = a*1000
In [14]: timeit ''.join(chr(i) for i in a if i)
1000 loops, best of 3: 1.44 ms per loop
In [15]: timeit str(bytearray(filter(None, a)))
1000 loops, best of 3: 259 µs per loop
In [16]: timeit ''.join(map(chr, filter(None, a)))
1000 loops, best of 3: 911 µs per loop
编辑:
在两个Python 2/3版本上工作的bytearray
方法如下所示:
>>> bytearray(filter(None, a)).decode('ascii')
'francesco'
在Python 3中,要将ascii序号列表转换为bytestring,可以: 要删除尾随的零字节,可以调用: 如果输入应在第一个零字节处停止(如C字符串——NUL终止): 要删除所有零字节(无论它们位于何处),请调用: 要获取Unicode字符串,请调用: 要使其同时在Python 2和Python 3上工作,请执行以下操作:
这些方法的性能与bytearray(filter(None,a))的
解决方案相当或更好。我使用了您的第二个解决方案。谢谢@没问题。我为你得到的三个解决方案添加了一些计时。@timgeb…这是Python2还是3?@timgeb…只是因为我在Python3中尝试了str(bytearray(filter(None,a))
,它给了我“bytearray(b'francesco')”
。@IronFist在Python3中,bytearray(filter(None,a))。解码('ascii')
。
>>> bytearray(filter(None, a)).decode('ascii')
'francesco'
>>> a = [102, 114, 97, 110, 99, 101, 115, 99, 111, 0, 0, 0, 0, 0, 0, 0]
>>> bytes(a)
b'francesco\x00\x00\x00\x00\x00\x00\x00'
>>> bytes(a).rstrip(b'\0')
b'francesco'
>>> import ctypes
>>> ctypes.create_string_buffer(bytes(b)).value
b'francesco'
>>> bytes(a).replace(b'\0', b'')
b'francesco'
>>> bytes(a).rstrip(b'\0').decode('ascii')
'francesco'
>>> bytearray(a).rstrip(b'\0').decode('ascii')
'francesco'