I'm trying to do the following:
>>>func = lambda string,i=0: string[index]
>>> func('HEY')
H
>>> func('HEY')
E
>>> func('HEY')
Y
How can i save and increment index each time(without creating index as global) thanks
Solution 1
You can create a generator function, like this
def get_next_char(actual_string):
for char in actual_string:
yield char
Then, you need to create a generator object, like this
next_char = get_next_char("HEY")
That's it. You can now get the next character with next
function, like this
>>> next(next_char)
H
>>> next(next_char)
E
>>> next(next_char)
Y
Solution 2
You can simply use the String's iterator, like this
get_char = iter("HEY")
>>> next(get_char)
H
>>> next(get_char)
E
>>> next(get_char)
Y
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.