strip module bug

Tim Chase python.list at tim.thechases.com
Mon Oct 13 09:21:06 EDT 2008


> I'm using versions 2.5.2 and 2.5.1 of python and have encountered a 
> potential bug. Not sure if I'm misunderstanding the usage of the strip 
> function but here's my example.
> 
> var = "detail.xml"
> print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
> var = "overview.xml"
> print var.strip(".xml") ### expect and get 'overview'

.strip() takes a *set* of characters to remove, as many as are found:
       _______    _____
  >>> 'xqxqxqxyxxyxqxqx'.strip('xq')
  'yxxy'

Using .replace() may work, but might have some odd side effects:

  >>> 'something.xml.zip'.replace('.xml')
  'something.zip'
  >>> 'this file has .xml in its name.xml'.replace('.xml')
  'this file has  in its name'

This also has problems if your filename and extension differ in 
case (removing ".xml" from "file.XML")

If you want to remove the extension, then I recommend using the 
python builtin:

   >>> import os
   >>> results = os.path.splitext('this has .xml in its name.xml')
   >>> results
   ('this has .xml in its name', '.xml')
   >>> fname, ext = results

Or, if you know what the extension is:

   >>> fname = 'this file has .xml in its name.xml'
   >>> ext = '.xml'
   >>> fname[:-len(ext)]
   'this file has .xml in its name'

Just a few ideas that are hopefully more robust.

-tkc







More information about the Python-list mailing list