Cutting a string in equal pieces

Gribouillis Gribouillis is offline Offline Jul 30th, 2008, 7:04 pm |
0
This snippet shows a fast and efficient way to cut strings in substrings with a fixed length (note that the last substring may be smaller).
Quick reply to this message  
Python Syntax
  1. import re
  2. split5 = re.compile(r".{1,5}", re.DOTALL).findall
  3.  
  4. if __name__ == "__main__":
  5. print split5('"Give me bacon and eggs," said the other man.')
  6. # prints ['"Give', ' me b', 'acon ', 'and e', 'ggs,"', ' said', ' the ', 'other', ' man.']
0
Gribouillis Gribouillis is offline Offline | Jul 31st, 2008
An alternative is this
  1. splitIt = lambda d, s: [s[i:i+d] for i in range(0, len(s), d)]
  2.  
  3. if __name__ == "__main__":
  4. print splitIt(5, '"Give me bacon and eggs," said the other man.')
 
0
Gribouillis Gribouillis is offline Offline | Oct 20th, 2009
The following benchmark shows that, on my machine, split5() is about 22% faster than splitIt()
  1. # benchmark for split5 and splitIt (tested with python 2.6)
  2. from timeit import Timer
  3. import re
  4. split5 = re.compile(r".{1,5}", re.DOTALL).findall
  5. splitIt = lambda d, s: [s[i:i+d] for i in range(0, len(s), d)]
  6.  
  7. if __name__=='__main__':
  8.  
  9. t = Timer("split5('Give me bacon and eggs, said the other man.')", "from __main__ import split5")
  10. print "split5: %.2f microsec" % t.timeit()
  11. t = Timer("splitIt(5, 'Give me bacon and eggs, said the other man.')", "from __main__ import splitIt")
  12. print "splitIt: %.2f microsec" % t.timeit()
  13.  
  14. """ my output --->
  15. split5: 2.55 microsec
  16. splitIt: 3.27 microsec
  17. """
however, you can gain 0.2 microsecs by replacing range with xrange in splitIt()
Last edited by Gribouillis; Oct 20th, 2009 at 2:53 pm.
 
0
lrh9 lrh9 is offline Offline | Oct 20th, 2009
I wonder how list slicing or struct.unpack() would work.
 
0
bumsfeld bumsfeld is offline Offline | Oct 20th, 2009
Seems to me that you also have to consider the time that re.compile() needs.
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC