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

Robert Kern robert.kern at gmail.com
Thu Sep 14 11:57:46 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?

Nothing. This is what I would do:


In [34]: s
Out[34]: 'abc\x00garbage'

In [35]: s.split('\x00', 1)[0]
Out[35]: 'abc'

In [36]: s.split?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in method split of str object at 0x6ada2c8>
Namespace:      Interactive
Docstring:
     S.split([sep [,maxsplit]]) -> list of strings

     Return a list of the words in the string S, using sep as the
     delimiter string.  If maxsplit is given, at most maxsplit
     splits are done. If sep is not specified or is None, any
     whitespace string is a separator.


Using the maxsplit argument saves split from having to do unnecessary work 
splitting the garbage portion if there are nulls there, too.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list