我有一個字節串,打印字節包含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
並沒有像我期望的那樣結束,怎麼做對不對?
我有一個字節串,打印字節包含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
並沒有像我期望的那樣結束,怎麼做對不對?
>>> str[:str.find('\0')]
'string ends with null'
Python字符串是不 NUL終止像C字符串。順便說一句,調用字符串str
是一個壞主意,因爲它會遮蓋內置類型str
。
候補@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字符串不是空值終止的
另一個可選的辦法是使用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']
注意,謝謝;-)。 – Alcott