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

Michael MichaelDMcDonnell at yahoo.com
Thu Sep 14 00:42:40 EDT 2006


Thank you very much for your responses. To answer some of the
questions... Yes, I am in Python receiving a C language 0 terminated
string that was sent to my Python program in a UDP packet (which is how
I know the count). Are your responses still correct given this
clarification?

Thanks much,
MDM

John Machin wrote:
> 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