| | |
Cutting a string in equal pieces
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
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 |
Tag cloud for Python
accessdenied address ansi backend beginner changecolor class code conversion coordinates copy curves customdialog dan08 dictionary directory dynamic edit examples excel feet file float font format ftp function generator getvalue gui halp homework i/o images import info input ip java line linux list lists loop mouse mysql newb number numbers output panel parsing path port prime print program programming projects py2exe pygame pyqt python queue random rational recursion recursive schedule screensaverloopinactive scrolledtext searchingfile server ssh stamp statictext string strings sudokusolver table terminal text thread threading time tkinter tlapse tuple tutorial type ubuntu unicode url urllib urllib2 variable whileloop windows write wxpython



