2

I face this peculiar situation:

I am using str format to give my filenames a certain pattern. For example I am using a prefix and then a fixed-length number to create the filename. The problem occurred when I needed to also control the fixed-length number length:

prefix = 'action1'
n = 6    
for i in range(0, 6):
    filename = '{}_{:06}.jpg'.format(prefix, i)
    print(filename)

action1_000000.jpg
action1_000001.jpg
...

I came up with this idea which combines old and new style string formatting but it's peculiar and surely prone to being deprecated:

n = 4    
for i in range(0, 6):
    filename = ('{}_{:0%d}.jpg' % n).format(prefix, i)
    print(filename)

action1_0000.jpg
action1_0001.jpg
...

So, is there any other approach to control the string format (the :06 part) inside a string format ({}_{:06}.jpg)?

2 Answers 2

2

You can use {} inside {} in str.format(). Try this:

'{}_{:0{}}.jpg'.format(prefix, i, 4)

See at "Nesting arguments and more complex examples" at this link

Or, using the f-string feature:

prefix = 'action1'
n = 4
for i in range(0, 6):
    filename = f'{prefix}_{i:0{n}}.jpg'
    print(filename)
Sign up to request clarification or add additional context in comments.

Comments

0

Why not use .rjust()?

prefix = 'action1_'
n = 6
counter = 1
filename = prefix + str(counter).rjust(n, '0')
print(filename)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.