Skip to content
Advertisement

integer formatting does not work in Python

I am trying to save my images with the time epoch plus iterating integers like this:

text_img.save('/content/result/' + epoch + '_%03d' + '.png' , format="png")

However, the output is something like this:

16087965_%03d.jpg

The formatting does not work for some reason. I do not know why.

Advertisement

Answer

At the moment, '_%03d' is just a literal string. Since your code is in a loop, you’ll want to provide the loop counter variable to be formatted.

Try something like:

import time

for i in range(100):
    epoch = str(int(time.time() / 1000))
    name = '/content/result/' + epoch + '_%03d' % i + '.png'
    text_img.save(name, format='png')

Or you can instead achieve the same thing using f-strings:

import time

for i in range(100):
    epoch = str(int(time.time() / 1000))
    name = f'/content/result/{epoch}_{i:03}.png'
    text_img.save(name, format='png')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement