How to delete a last character from a string

Fredrik Lundh fredrik at pythonware.com
Fri Aug 29 14:50:28 EDT 2008


dudeja.rajat at gmail.com 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
name\
 >>> print repr(item)
'name\\'
 >>> item.endswith("\\")
True
 >>> if item.endswith("\\") == True:
...     print item[:-1]
...
name

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).

</F>




More information about the Python-list mailing list