fork download
  1. #!/usr/bin/python
  2. """
  3. $Id$
  4.  
  5. Purpose:
  6. Demonstrate the way the struct module works.
  7.  
  8. Description:
  9. One can access substrings of a string in a arbitrary manner while using the
  10. struct module. This is mostly useful when dealing with byte level
  11. programming required in embedded systems or while using sockets.
  12.  
  13. Source:
  14. Python cookbook perhaps.
  15. """
  16. import struct
  17. theline = "The quick brown fox jumped over the lazy dog."
  18. # Get a 5-byte string, skip 3, get two 8-byte string, then all the rest:
  19. baseformat = '5s 3x 8s 8s'
  20. # by how many bytes does theline exceed the length implied by this
  21. # base-format ( 24 bytes in this, but struct.calcsize is general)
  22. numremain = len(theline) - struct.calcsize(baseformat)
  23. # complete the format with the appropriate 's' field, then unpack
  24. format = '%s %ds' % (baseformat, numremain)
  25. l, s1, s2, t = struct.unpack(format, theline)
  26. print l
  27. print s1
  28. print s2
  29. print t# your code goes here
Success #stdin #stdout 0s 23304KB
stdin
Standard input is empty
stdout
The q
k brown 
fox jump
ed over the lazy dog.