| | |
Cutting a string in equal pieces
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).
import re split5 = re.compile(r".{1,5}", re.DOTALL).findall if __name__ == "__main__": print split5('"Give me bacon and eggs," said the other man.') # prints ['"Give', ' me b', 'acon ', 'and e', 'ggs,"', ' said', ' the ', 'other', ' man.']
0
•
•
•
•
An alternative is this
python Syntax (Toggle Plain Text)
splitIt = lambda d, s: [s[i:i+d] for i in range(0, len(s), d)] if __name__ == "__main__": print splitIt(5, '"Give me bacon and eggs," said the other man.')
0
•
•
•
•
The following benchmark shows that, on my machine, split5() is about 22% faster than splitIt()
however, you can gain 0.2 microsecs by replacing range with xrange in splitIt()
python Syntax (Toggle Plain Text)
# benchmark for split5 and splitIt (tested with python 2.6) from timeit import Timer import re split5 = re.compile(r".{1,5}", re.DOTALL).findall splitIt = lambda d, s: [s[i:i+d] for i in range(0, len(s), d)] if __name__=='__main__': t = Timer("split5('Give me bacon and eggs, said the other man.')", "from __main__ import split5") print "split5: %.2f microsec" % t.timeit() t = Timer("splitIt(5, 'Give me bacon and eggs, said the other man.')", "from __main__ import splitIt") print "splitIt: %.2f microsec" % t.timeit() """ my output ---> split5: 2.55 microsec splitIt: 3.27 microsec """
Last edited by Gribouillis; Oct 20th, 2009 at 2:53 pm.
Similar Threads
- Cutting Down String Split Overhead (Visual Basic 4 / 5 / 6)
- split a string of words into pieces and print (Python)
- Sorting using pieces of a struct (C++)
- need help finishing the last pieces i haven't finshed yet using c (C)
- JSP/ JavaScript few simple pieces (Web Development Job Offers)
| Thread Tools | Search this Thread |
address alarm anydbm app beginner cipher conversion coordinates curves cx-freeze data development dictionary directory dynamic examples excel feet file float format function generator getvalue gui halp handling homework images import input ip itunes java keycontrol line linux list lists loan loop maintain maze millimeter mouse mysqldb number numbers output parsing path port prime programming projects py2exe pygame pyglet pymailer python queue random recursion recursive screensaverloopinactive script scrolledtext searchingfile shebang slicenotation split ssh string strings table terminal text thread threading time tlapse tooltip tuple tutorial type ubuntu unicode url urllib urllib2 variable variables ventrilo verify vigenere web webservice wx.wizard wxpython xlwt



