strip module bug

Peter Otten __peter__ at web.de
Mon Oct 13 09:07:08 EDT 2008


Poppy wrote:

> 
> 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'
> 
> I have a work around using the replace function which happens to be the
> better choice for my script anyhow. But am curious about the strip module.
> Any thoughts? Is it removing the 'l' in detail because the strip function
> text ends in 'l'?

The behaviour you intend, stripping a suffix, is achieved by

>>> var = "detail.xml"
>>> suffix = ".xml"
>>> if var.endswith(suffix):
...     var = var[:-len(suffix)]
...

The var.strip(chars) /method/ does something different. It treats chars as a
set of characters and removes any of these characters from the end and the
beginning of the var string, i. e.

"detail.xml" d is not in ".xml" -> remove no further chars from the
beginning
"detail.xml" l is in ".xml", remove it
"detail.xm" m is in ".xml", remove it
"detail.x" x is in ".xml", remove it
"detail." . is in ".xml", remove it
"detail" l is in ".xml", remove it
"detai" i is not in ".xml", we're done

Peter



More information about the Python-list mailing list