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

John Machin sjmachin at lexicon.net
Thu Sep 14 01:14:27 EDT 2006


Michael top-posted [corrected]:
> 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
> 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?

My responses are correct. Your "clarification" indicates to me that you
are going by what you are told, not by inspection of (several instances
of) the packet contents, using repr(). It's up to you whether you want
to be skeptical about the packet contents or not. I certainly wouldn't
be throwing the last byte away without checking that it was in fact a
NUL. 

Cheers,
John




More information about the Python-list mailing list