itertools module in python code example
Example 1: python itertools repeat()
# How to use it:
# repeat(var, amount)
# repeat() is basically like range() but it gives an extra arg for a var
from itertools import repeat
for x in repeat("Spam? Or Eggs?", 3):
print(x)
> "Spam? Or Eggs?"
> "Spam? Or Eggs?"
> "Spam? Or Eggs?"
Example 2: itertools.zip_longest fill value
from itertools import zip_longest
chars = []
correct = 'hangman'
guess = 'winger'
for c, g in zip_longest(correct, guess, fillvalue='_'):
if c == g:
chars.append(c)
else:
chars.append('_')
print(chars)
# ['_', '_', 'n', 'g', '_', '_', '_']
word = ''.join(chars)
print(word)
# __ng___