2014-01-15 188 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']