How to delete a last character from a string

Fredrik Lundh fredrik at
Fri Aug 29 20:50:28 CEST 2008

dudeja.rajat at wrote:

> I've a list some of whose elements with character \.
> I want to delete this last character from the elements that have this
> character set at their end,
> I have written a small program, unfortunately this does not work:
> dirListFinal = []
> for item in dirList:
>            print item
>            if item.endswith('\\') == True:

explicitly comparing against true is bad style; better write that as

              if item.endswith('\\'):

>                item = item[0:-1]         # This one I googled and
> found to remove the last character /
>                dirListFinal.append(item)
>            else:
>                dirListFinal.append(item)
> item.endswith() does not seem to be working.

item.endswith("\\") works just fine:

 >>> item = "name\\"
 >>> print item
 >>> print repr(item)
 >>> item.endswith("\\")
 >>> if item.endswith("\\") == True:
...     print item[:-1]

instead of assuming that some builtin function is broken, try printing 
the the value of item to check that it really contains what you think it 
does.  (use print repr(item) to see control characters etc).


More information about the Python-list mailing list