Equivalent for pop on strings

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

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

What is a nice and efficient way of doing this?

3

4 Answers

You can wrap the string in a StringIO or BytesIO and pretend it's a file. That 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 
7

you can convert the string to a list. list(string) and pop it, or you could iterate in chunks slicing the list [] or you can slice the string as is and iterate in chunks

You can do this with slicing:

large_string = "foobar..." while large_string: process(large_string[-200:]) large_string = large_string[:-200] 
1

To follow up on 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' 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like