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?
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)
you can do it using string indexes, like it's list:
for i in xrange(100, 200):
print(s[i])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With