Issue
So I have a string source
, over which I loop with an iterator:
iterator = iter(source)
for char in iterator:
do stuff
However, now say that I have a check in do stuff
, where I compare the value of the iterator to 'h'. Then I want to see if the 'h' is followed by "ello ", in some way, and add the first ten characters after that to a list.
For this my own idea would be to find out which index corresponds with the current position of the iterator, so that I can say:
indIt = index(char)
if source[indIt + 1: indIt + 6] == "ello ":
someList.append(source[indIt + 7:indIt + 16])
indIt += 17
char = indIt #which may also be fun to know how it can be done, if
This would mean that for given input hello Sandra, oh and hello Oscar, i welcome you both!
, someList
would contain ["Sandra, oh", "Oscar, i w"].
So can I, in some way, figure out to which index the current position of an iterator corresponds?
Solution
Iterators don't expose an index, because there doesn't have to be a sequence underlying one.
Use the enumerate()
function to add one to your iteration:
for index, char in enumerate(iterator):
Now iteration produces (index, value)
tuples, which you can assign to two separate variables using tuple assignment.
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.