user2170780
user2170780

Reputation: 1207

Python: Converting to str while keeping leading 0's

So in python I'm trying to access a file path in the order of 000X

So I start by setting a string to

path = '0001'

and then point to and open the file path

filepath = open('/home/pi/Pictures' + path + '.JPG', 'rb')

so I do my business and now want to access the next file of extension 0002

intpath = int(path)
intpath = intpath + 1
path = str(intpath)

I'm sure this is inefficient, but I'm starting out. Unfortunately, this makes path '2' and not '0002'....any idea how I can maintain the leading zeros?

Upvotes: 2

Views: 493

Answers (4)

John La Rooy
John La Rooy

Reputation: 304355

Another advantage of str.format is that it's easy to parameterise the width. If your Python is 2.5 or older you'll have to use the % formatting

>>> ['{i:0{width}}'.format(i=i, width=4) for i in range(1, 15)]
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0014']

Upvotes: 0

mgilson
mgilson

Reputation: 310049

I'd probably use one of the others, but for completeness, there's also zfill:

'1'.zfill(4)

Upvotes: 0

dsh
dsh

Reputation: 12214

If you know that you need 4 digits, use string formatting:

path = "%04d" % (intpath+1)

Upvotes: 2

jamylak
jamylak

Reputation: 133634

You can use something like this

>>> ['{0:04}'.format(i) for i in range(1, 15)]
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', 
 '0010', '0011', '0012', '0013', '0014']

Upvotes: 3

Related Questions