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

Michael MichaelDMcDonnell at yahoo.com
Thu Sep 14 11:42:52 EDT 2006


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?

Marc 'BlackJack' Rintsch wrote:
> In <1158247587.541483.266640 at k70g2000cwa.googlegroups.com>, John Machin
> wrote:
>
> > In other words, if the last byte of strg is NUL, throw it away.
> >
> > The truly paranoid would code that as
> >     if strg and strg[-1] etc etc
> > so that it wouldn't blow up if strg is empty -- strange things can
> > happen when you are reading other people's data :-)
>
> I would spell it:
>
> if strg.endswith('\0'):
>     strg = strg[:-1]
> 
> Ciao,
> 	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list