[Tutor] more fun and games with padded numbers
Terry Carroll
carroll at tjc.com
Fri Jan 12 04:24:19 CET 2007
On Thu, 11 Jan 2007, Christopher Spears wrote:
> Let's say I have a series of files that are named like
> so:
>
> 0001.ext
> 0230.ext
> 0041.ext
> 0050.ext
>
> How would I convert these from a padding of 4 to a
> padding of 1? In other words, I want the files to be
> renamed as:
>
> 1.ext
> 230.ext
> 41.ext
> 50.ext
That doesn't look to me like a padding of 1; that looks to me like no
padding.
But if that's what you want, I'm sure there's a better way, but my initial
approach would be:
>>> oldnames = ["0001.ext", "0230.ext", "0041.ext", "0050.ext"]
>>> for name in oldnames:
... newfname, fext = name.split('.')
... newname = "%s.%s" % (int(newfname), fext)
... print newname
...
1.ext
230.ext
41.ext
50.ext
>>>
Note that this assumes that the filename portion is entirely numeric.
This would break on, for example, a file named 00abc.ext.
Actually, what I don't like here is the conversion of string to int to
string for no real purpose.
> At first I used strip(), which was a mistake because
> it removed all the zeroes.
That should work, with an argument:
>>> oldnames = ["0001.ext", "0230.ext", "0041.ext", "0050.ext"]
>>> newnames = [name.strip('0') for name in oldnames]
>>> newnames
['1.ext', '230.ext', '41.ext', '50.ext']
More information about the Tutor
mailing list