我有一个字节字符串,
str = 'string ends with null\x00\x11u\x1ai\t'我希望str应该在单词null之后终止,因为NULL \x00紧随其后,但是当我打印str时,
>>> print('string ends with null\x00\x11u\x1ai\t')
string ends with nulluistr并没有像我预期的那样结束,如何纠正它?
发布于 2014-01-15 10:07:56
>>> str[:str.find('\0')]
'string ends with null'Python字符串并不像C字符串那样以NUL结尾。顺便说一句,调用字符串str是个坏主意,因为它隐藏了内置类型str。
发布于 2014-01-15 10:11:18
替代@larsman提供的内容,您也可以使用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中的字符串不以空终止。
发布于 2014-01-15 10:16:56
另一种选择是使用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']https://stackoverflow.com/questions/21134370
复制相似问题