Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through python string starting at index

If I have a very long string (say 100 million characters), is there a way to iterate through the characters using something like for c in str: but starting a certain number of characters in? I'd prefer not to slice the string and use a subset, because I understand that slicing the string will make a copy (very expensive in my case). In other words, can I specify a start point for an iterator over a string?

like image 276
user2667066 Avatar asked Oct 12 '15 10:10

user2667066


2 Answers

In python3 range is an generator, and not a list. That means that the following code will not require excessive memory:

for i in range(start_pos, len(my_string)):
   print(my_string[i])

If you'd rather use an iterator over my_string then you need to write it yourself:

def iter_starting_at(start_pos, string):
    for i in range(start_pos, len(string)):
        yield string[i]

for character in iter_starting_at(start_pos, my_string):
    print(character)
like image 188
Régis B. Avatar answered Sep 27 '22 23:09

Régis B.


you can do it using string indexes, like it's list:

for i in xrange(100, 200):
    print(s[i])
like image 30
Eugene Soldatov Avatar answered Sep 28 '22 01:09

Eugene Soldatov