How do I converted a null (0) terminated string to a Python string?

John Machin sjmachin at lexicon.net
Thu Sep 14 18:04:08 EDT 2006


Michael wrote:
> I guess, I still don't see how this will work. I'm receiving a C
> zero-terminated string in my Python program as a 1K byte block (UDP
> datagram). If the string sent was "abc", then what I receive in Python
> is <a><b><c><0><garbage><garbage>...<last_garbage_byte>. How is Python
> going to know where in this 1K byte block the end of the string is? It
> seems that what I need to do is tell Python that the string ends at
> zero-relative index 3. What am I missing here?
>

You are missing this, contained in the third message in this thread
i.e. my first reply to you:
"""
It's possible you may be talking about a fixed length string which
contains useful_stuff + "\0" + padding -- in that case you need

strg = strg.split("\0")[0] # grab upto (but not including) the first
NUL (if any)
"""

Please note that Robert Kern's solution is better than the above (as he
says, it won't waste time splitting up the garbage, the mind-boggling
relative size of which I hadn't catered for).

You are also missing the frequent (3 at last count) exhortations to:
    print repr(your_string)
which is much more precise than verbal descriptions.

Cheers,
John




More information about the Python-list mailing list