Maintaining leading zeros with the lstrip string function?

Carsten Haese carsten at
Mon Jul 23 21:24:20 CEST 2007

On Mon, 2007-07-23 at 11:41 -0700, Randy Kreuziger wrote:
> I need just the file name from a string containing the path to a file.
> The name of the file starts with zeros.  This is problematic because
> the  lstrip function strips them leaving this as the result:
> 6128.jpg
> How do I strip the path without losing the leading zeros in the file
> name?
> —---------------------------------------------
> import sys, os, win32com.client, string
> teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg'
> print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\')

You're using the wrong tool for the job. lstrip removes any contiguous
string consisting of any of the characters in the string you give it.
You would have achieved the same wrong result with

teststring.lstrip(" 08:C\\adehilnoprsvx")

As you have discovered, this hungry caterpillar will eat the leading
zeroes of your filename. It doesn't see any difference between the
zeroes before the last \ and the zeroes after the last \. It just eats
them all. If the leading zeroes had been followed by an 8, it would have
eaten that, too.

The right tool for the job is os.path, more specifically


Carsten Haese

More information about the Python-list mailing list