I want to format some values that are in a generator. When I try to do that I get an error:
TypeError: unsupported format string passed to generator.__format__
I tried different types of string formatting and nothing worked.
This is my code:
def gen_secs():
for i in range (60):
yield i
def gen_minutes():
for i in range (60):
yield i
def gen_hours():
for i in range (24):
yield i
def gen_time(hours,minutes,seconds):
yield (f'{hours:02}:{minutes:02}:{seconds:02}')
seconds = gen_secs()
minutes = gen_minutes()
hours = gen_hours()
gt = gen_time(hours,minutes,seconds)
while True:
print(next(gt))
I want to get back all the different combinations of times in a day.
00:00:00
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
00:00:06
and so on...
You have a few problems here.
One is that your main generator gen_time
yields one time so at best, eliminating all other issues, you will get only one time.
you pass to your gen_time
the generator objects as arguments. Then you are formatting the string on the generator objects themselves and not their elements and hence your error.
You use a while True
loop on the generator which will throw a StopIteration
and break your program. I'm not sure that's what you want.
To solve this, taking in count point (1), you want some kind of loop wrapping your yield
in the main generator. So, you could alter your main generator, gen_time
to loop on the other generators. Like so:
def gen_time():
for hours in gen_hours():
for minutes in gen_minutes():
for seconds in gen_secs():
yield (f'{hours:02}:{minutes:02}:{seconds:02}')
You could also write that more compact using the yield from
construct:
def gen_time():
yield from (f'{hours:02}:{minutes:02}:{seconds:02}' for hours in gen_hours() for minutes in gen_minutes() for seconds in gen_secs())
Now considering point (3) you can change your main code to:
for gt in gen_time():
print(gt)