[Python] Format string template defined outside of loop? [duplicate]

Discussão em 'Python' iniciado por Stack, Novembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I'm getting odd results when defining a format string outside of a loop. I want to define a variable containing my format string like:

    MYSTRING = f"filepath/{year}/{month}"


    If I define it outside the loop I get repeated same value. If I copy/paste that string inside the loop it works fine.

    This one goes all the way back to 2023 as expected:

    last_n_months = 12
    months = date.today().year * 12 + date.today().month - 1 # Months since year 0 minus 1
    tuples = [((months - i) // 12, (months - i) % 12 + 1) for i in range(last_n_months)]

    for item in tuples:
    year = str(item[0])
    month = str(item[1])
    # string used in directly with the format() function
    print(f"xyz/Year={year}/Month={month}".format())

    ------------------------
    xyz/Year=2024/Month=11
    xyz/Year=2024/Month=10
    xyz/Year=2024/Month=9
    xyz/Year=2024/Month=8
    xyz/Year=2024/Month=7
    xyz/Year=2024/Month=6
    xyz/Year=2024/Month=5
    xyz/Year=2024/Month=4
    xyz/Year=2024/Month=3
    xyz/Year=2024/Month=2
    xyz/Year=2024/Month=1
    xyz/Year=2023/Month=12


    But this one repeats the same year/month for each:

    # the format string
    myformatstring = f"xyz/Year={year}/Month={month}"

    last_n_months = 12
    months = date.today().year * 12 + date.today().month - 1 # Months since year 0 minus 1
    tuples = [((months - i) // 12, (months - i) % 12 + 1) for i in range(last_n_months)]

    for item in tuples:
    year = str(item[0])
    month = str(item[1])
    # use the format string variable from outside the loop
    print(myformatstring.format())

    ------------------------
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12
    xyz/Year=2023/Month=12


    Any ideas?

    Continue reading...

Compartilhe esta Página