[Tutor] Looking at a String as a Struct?

Alan Gauld alan.gauld at btinternet.com
Fri Sep 12 01:00:51 CEST 2008

"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote

> lIs it possible in Python to look at a string as a "struct".
I assume you mean you have a lot of data all stored in a single 
I also assume that either the string has a fixed delimiter - like a 
separated file?
Or it has fixed length fields?

> I don't think a struct exists in python.

What is a struct? It is a data record that can hold different field 
So yes struct exists in Python in a multitude of forms:
a) a tuple is an immutable collection of items
b) a list is a mutable collection of items
c) a class without methods is most like a C struct

So you have a choice.
However I suspect that what you want is more like a C union.
And no Python does not have a union concept.

The best we can do is either use someting like a regex to
extract fields based on the separator or use the struct
module (now there's a clue?!) to extract fixed length fields
from a string of bytes. struct can e used for binary data but
it can also be used for fixed length string fields inside a
character string.

Once extracted move the new fields (with type conversion
as needed) into the fields of a class or into a tuple/list.
If you use a class you cancombine the decoding with
the assignment in the constructor (__init__ method)

You can read about all opf these data types in the
Raw Materials topic of my tutor. You can read about
classes in the OOP tiopic and you can read a bit
about struct in the File Handling topic.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list