简体   繁体   中英

TypeError: 'str' object is not callable in generator python

def gen_secs():
    x = 0
    while x < 60:
        yield x
        x += 1

def gen_minutes():
    x = 0
    while x < 60:
        yield x
        x += 1

def gen_hours():
    x = 0
    while x < 24:
        yield x
        x += 1

def gen_time():
    for x in gen_hours():
        for y in gen_minutes():
            for z in gen_secs():
                yield ("%d:%d:%d" (x, y, z))

for gt in gen_time():
    print(gt)
    if gt == "01:23:45":
        break

the the function gen_time cannot return the string param for some reason. there's syntax problem and I cannot find the issue.

update your function gen_time and make your time data in hh:mm:ss format as

def gen_time():
    for x in gen_hours():
        for y in gen_minutes():
            for z in gen_secs():
                a, b , c = x, y, z
                if x<10:
                    a = f'0{x}'
                if y<10:
                    b = f'0{y}'
                if z<10:
                    c = f'0{z}'
                yield (f"{a}:{b}:{c}")

You forget the format str syntax, try change the follow:

yield ("%d:%d:%d" (x, y, z))

to:

yield ("%d:%d:%d" % (x, y, z))

This article can be very helpful

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM