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

John Machin sjmachin at lexicon.net
Thu Sep 14 00:08:33 EDT 2006


Michael wrote:
> Hi All,
>
> I've received (via UDP) a null terminated string and need to convert it
> into a Python string. Can anyone tell me how this is done? If it helps,
> I know the number of characters in the string.
>

I think you mean NUL, not null.

What have you received it into, if it's not a Python string?

You probably need/want this:

if strg[-1] == "\0":
    strg = strg[:-1]
alternatively:
strg = strg.rstrip("\0") # requires Python 2.2.2 or later

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)

If you're not sure what you've got, print repr(the_input_string)

HTH,
John




More information about the Python-list mailing list