Reputation: 6197
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
Reputation: 2078
Use:
for i in range(1, 454):
downloadFunction('www.website.com/file'+str(i).rjust(3,'0')+'.mp3')
instead.
Upvotes: 1
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
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