我有一个字节串,打印字节包含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