SantoshGupta7
SantoshGupta7

Reputation: 6197

Most clean and pythonic way to concatenate numbers and strings in a loop while maintaining a prefix of zeros

Say I want to download files from websites and files are listed by this style

www.website.com/file001.mp3
www.website.com/file002.mp3
www.website.com/file003.mp3
.
.
.
www.website.com/file451.mp3
www.website.com/file452.mp3
www.website.com/file453.mp3

And I want to make some code that'll download these using a loop.

for i in range(1, 454):
    downloadFunction('www.website.com/file00'+i+'.mp3')

This would not work when i is bigger than 9 because then the concatenation would look like

'www.website.com/file0010.mp3' 

instead of

'www.website.com/file010.mp3' 

I could code the case for each hundreth's value but I have a feeling there is a more elegant way to code this.

Upvotes: 0

Views: 78

Answers (4)

msi_gerva
msi_gerva

Reputation: 2078

Use:

for i in range(1, 454):
    downloadFunction('www.website.com/file'+str(i).rjust(3,'0')+'.mp3')

instead.

Upvotes: 1

Woody1193
Woody1193

Reputation: 7980

You can do downloadFunction('www.website.com/file%03d.mp3' % i). The % is a placeholder and the d is a numeric format-specifier. The 03 tells Python to zero-pad up to three characters.

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24281

Using the a format string, you could do:

url_template = 'www.website.com/file{:03}.mp3'

for i in range(9, 12):
    print(url_template.format(i))

Output:

www.website.com/file009.mp3
www.website.com/file010.mp3
www.website.com/file011.mp3

So, for your application:

url_template = 'www.website.com/file{:03}.mp3'
for i in range(1, 454):
    downloadFunction(url_template.format(i))

Upvotes: 6

101
101

Reputation: 8999

You can use zfill, which is a string function that pads a string with leading zeroes. In your case:

for i in range(1, 454):
    downloadFunction('www.website.com/file{}.mp3'.format(str(i).zfill(3)))

Upvotes: 1

Related Questions