GlaceCelery
GlaceCelery

Reputation: 1043

Re-formatting the same string doesn't work. How can I achieve this?

I want to populate a base string in a loop, to access files with increasing calendar days in their name. This is the cut down version:

my_str = "filename_{}_blah.txt"
for n in range(3):
    my_str = my_str.format(n)
    print(my_str)

Output:

filename_0_blah.txt
filename_0_blah.txt
filename_0_blah.txt

I expected the numbers to increase.

(1) Is there a way around this,

(2) Why does this happen?

Thank you.

Upvotes: 1

Views: 87

Answers (5)

ToughMind
ToughMind

Reputation: 1009

As @Barmar has said, the problem in your code is that the variable my_str = "filename_{}_blah.txt" is changed to filename_0_blan.txt in the very first loop. So the code my_str.format(n) can do nothing afterwards.

I want to add a new solution which is available after python3.6:

for n in range(3):
    my_str = f'filename_{n}_blah.txt'

Upvotes: 1

Dv6
Dv6

Reputation: 489

Try this:

my_str = "filename_{}_blah.txt"
for n in range(3):
    print(my_str.format(n));

Upvotes: 1

amrs-tech
amrs-tech

Reputation: 483

You can try this code:

my_str = 'filename_{}_blah.txt'
str_list=[]
for n in range(3):
    str_list.append(my_str.format(n))
    print(str_list[n])

This gives your expected output. Hope it helps :)

Upvotes: 0

bluesummers
bluesummers

Reputation: 12627

(1) Yes there is

for n in range(3):
    my_str = "filename_{}_blah.txt".format(n)
    print(my_str)

(2) This happens because you already filled the {} in the string in the first iteration, so after that iteration the my_str actually becomes filename_0_blah.txt and there is nothing to format in it

Upvotes: 4

Barmar
Barmar

Reputation: 781726

You need to use a different variable to hold the format string and result. If you assign back to the same variable, it no longer contains the format string, the {} has been replaced with the value of n. So the next time, there's no placeholder to replace with the next value of n.

format_str = "filename_{}_blah.txt"
for n in range(3):
    my_str = format_str.format(n)
    print(my_str)

Upvotes: 7

Related Questions