Equivalent to string strings

Given a very large string. I would like to handle the parts of a string in a loop like this:

large_string = "foobar..." while large_string: process(large_string.pop(200)) 

What is a good and effective way to do this?

+9
source share
4 answers

You can wrap the string in StringIO or BytesIO and pretend to be a file. It should be pretty fast.

 from cStringIO import StringIO # or, in Py3/Py2.6+: #from io import BytesIO, StringIO s = StringIO(large_string) while True: chunk = s.read(200) if len(chunk) > 0: process(chunk) if len(chunk) < 200: break 
+13
source

you can convert a string to a list. list(string) and put it, or you can iterate in pieces by slicing the list [] , or you can chop the string as is and iterate in pieces

+9
source

You can do this with slicing :

 large_string = "foobar..." while large_string: process(large_string[-200:]) large_string = large_string[:-200] 
+3
source

To continue dm03514's answer, you can do something like this:

 output = "" ex = "hello" exList = list(ex) exList.pop(2) for letter in exList: output += letter print output # Prints 'helo' 
0
source

All Articles