R S John
R S John

Reputation: 515

File naming inside a for loop

Please have a look on the following Minimal Working Example (MWE)

import numpy as np
T_val = np.linspace(100,200,15)
for i,T in enumerate(T_val):
    ut_file_name = 'kappaFunction_P_E_%2d.pdf' % i
    print out_file_name

The output for this MWE coming like:

.
.
kappaFunction_P_E_ 7.pdf
kappaFunction_P_E_ 8.pdf
kappaFunction_P_E_ 9.pdf
kappaFunction_P_E_10.pdf
kappaFunction_P_E_11.pdf
kappaFunction_P_E_12.pdf
.
.

What I intended to get is

... kappaFunction_P_E_08.pdf, kappaFunction_P_E_09.pdf, kappaFunction_P_E_10.pdf....

Instead of prepending 0 before the single digit number it is leaving a space. How can we get rid of this?

Upvotes: 0

Views: 79

Answers (3)

Windyground
Windyground

Reputation: 119

ut_file_name = 'kappaFunction_P_E_{:0>2}.pdf'.format(i)

Your should use format(). You can reference from https://pyformat.info/ or docs from https://docs.python.org/2/library/string.html.

Upvotes: 2

Cyrbil
Cyrbil

Reputation: 6478

You don't need to use enumerate since your are only using the index. And for your format to work as expected, you need to use %02d to get the 0 before:

import numpy as np
T_val = np.linspace(100,200,15)
for i in range(len(T_val)):
    ut_file_name = 'kappaFunction_P_E_%02d.pdf' % i
    print out_file_name

Upvotes: 1

C14L
C14L

Reputation: 12558

Add a 0 to the format

... %02d.pdf' % i

that will print 07, 08, 09, etc.

Upvotes: 1

Related Questions