打印包含NULL的字节

2024-10-01 04:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字节字符串

str = 'string ends with null\x00\x11u\x1ai\t'

我希望str应该在单词null之后终止,因为空的\x00紧跟其后,但是当我打印str

>>> print('string ends with null\x00\x11u\x1ai\t')
string ends with nullui

str没有像我预期的那样结束,如何使它正确?你知道吗


Tags: 字符串string字节with单词nullprintx00
3条回答
>>> 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结尾的

另一种选择是使用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']

相关问题 更多 >