0

I have a bytes string,

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

and I expect that str should terminate after the word null, because a NULL \x00 follows immediately, however when I print str,

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

str doesn't end as I expected, how to make it right?

3 Answers 3

4
>>> str[:str.find('\0')]
'string ends with null'

Python strings are not NUL-terminated like C strings. Btw., calling a string str is a bad idea as it shadows the built-in type str.

Sign up to request clarification or add additional context in comments.

Comments

2

Alternate to what @larsmans provided, you can also use 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'

And as always unlike C/C++, strings in python are not Null Terminated

Comments

1

Another alternate would be to use 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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.