2014-01-15 189 views
0

我有一个字节串,打印字节包含NULL

str = 'string ends with null\x00\x11u\x1ai\t' 

,我想到的是str应字null后,当我打印str终止,因为一个NULL \x00紧随其后,然而,

>>> print('string ends with null\x00\x11u\x1ai\t') 
string ends with nullui 

str并没有像我期望的那样结束,怎么做对不对?

回答

4
>>> str[:str.find('\0')] 
'string ends with null' 

Python字符串是 NUL终止像C字符串。顺便说一句,调用字符串str是一个坏主意,因为它会遮盖内置类型str

+0

注意,谢谢;-)。 – Alcott

2

候补@larsmans提供什么,你也可以使用ctypes.c_char_p

>>> from ctypes import * 
>>> st = 'string ends with null\x00\x11u\x1ai\t' 
>>> c_char_p(st).value 
'string ends with null' 

和往常不同C/C++,在python字符串不是空值终止的

1

另一个可选的办法是使用split

>>> str = 'string ends with null\x00\x11u\x1ai\t\x00more text here' 
>>> str.split('\x00')[0] 
'string ends with null' 
>>> str.split('\x00') 
['string ends with null', '\x11u\x1ai\t', 'more text here']