2024-10-01 04:46:01 发布
网友
我有一个字节字符串
str = 'string ends with null\x00\x11u\x1ai\t'
我希望str应该在单词null之后终止,因为空的\x00紧跟其后,但是当我打印str
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字符串不像C字符串那样以NUL结尾。顺便说一句,调用字符串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中的字符串不是以Null结尾的
C/C++
另一种选择是使用split:
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']
Python字符串不像C字符串那样以NUL结尾。顺便说一句,调用字符串
str
是个坏主意,因为它会隐藏内置类型str
。你知道吗除了@larsmans提供的以外,还可以使用ctypes.c_char_p
与
C/C++
不同的是,python中的字符串不是以Null结尾的另一种选择是使用
split
:相关问题 更多 >
编程相关推荐