user3295674
user3295674

Reputation: 913

Leading/prefix 0s in out of for loop

I am writing a four loop in my program that writes data to a file. I'm wanting for the output to be formatted as follows

frame001 + K.1
frame002 + K.2
...
frame099 + K.99
frame100 + K.100

So far I am doing

for f in range(1, 100):
    file.write('frame' + str(f) + ' + K.' + str(f) + '\n')

I have no problem having the K part come out correctly as K.1-K.100, but I don't know how to have prefix zeros/have it output also frame00F to frameFFF with the appropriate amount of preceding zeros.

Upvotes: 0

Views: 87

Answers (1)

falsetru
falsetru

Reputation: 369304

Using str.format:

>>> 'frame{0:03d} + K.{0}\n'.format(1)
'frame001 + K.1\n'
>>> 'frame{0:03d} + K.{0}\n'.format(100)
'frame100 + K.100\n'

BTW, range(1, 100) will not yield 100. If you want 100 to be included, that should be range(1, 101).


If you are using old version of Python (Python 2.5-), use % operator (String formatting operator) instead (need to specify multiple argument unlike str.format)

>>> 'frame%03d + K.%d\n' % (1, 1)
'frame001 + K.1\n'
>>> 'frame%03d + K.%d\n' % (100, 100)
'frame100 + K.100\n'

If you don't want to repeat arguments, you can pass mapping instead with slightly different format specifier:

>>> 'frame%(i)03d + K.%(i)d\n' % {'i': 1}
'frame001 + K.1\n'

Upvotes: 2

Related Questions