How to delete a last character from a string

Derek Martin code at pizzashack.org
Fri Aug 29 16:46:00 EDT 2008


On Fri, Aug 29, 2008 at 07:37:50PM +0000, Steven D'Aprano wrote:
> On Fri, 29 Aug 2008 14:46:53 -0400, Derek Martin wrote:
> 
> > On Fri, Aug 29, 2008 at 07:28:40PM +0100, dudeja.rajat at gmail.com wrote:
> >> dirListFinal = []
> >> for item in dirList:
> >>            print item
> >>            if item.endswith('\\') == True:
> > 
> >              if item[-1] == '\\':
> 
> Which will fail badly if item is the empty string.

Sure.  I made 2 assumptions:

1. The OP didn't say how endswith() was failing.  My assumption was it
was missing from his version of python (i.e. he's using a version that
predates the feature).  I have no idea if that's possible or not...
I've used python 2.4 almost exclusively.  I've run into a number of
cases where some clever trick I found on-line didn't work because it
was new in Python 2.5 (or whatever), so it was easy for me to lazily
assume that it could be the case here.

2. If his particular use case didn't exclude the possibility of an
empty string, he'd be smart enough to check that first, or wrap it in
a try block.

> Rajat, rather than trying to invent your own code to join directory 
> paths, you should use the os.path module:
> 
> >>> import os
> >>> os.path.join('/dir', 'x', 'y', 'z', 'file.txt')

I agree completely, though I do find that there's one thing missing
from this module's support, which your example illustrates nicely: a
way to find out what the root of the current filesystem is (for some
definition of current which I will let the reader figure out).  You
explicitly wrote '/dir', which would likely be wrong on non-Unix OSes,
though IIRC it might work anyway, depending on your particular
environment (e.g. cygwin).

I usually end up doing this via the following function:

def _get_path_root(path):
    '''recursive algorithm to determine the name of the root of the file
    system in (hopefully) an os-independent way'''

    if os.path.dirname(path) == path:
        return path
    return _get_path_root(os.path.dirname(path))

You can, depending on your needs, either pass it the absolute path of
your script, or the absolute path of your data file(s).  For the sake
of performance, I get the real absoulte path outside function:

x = _get_path_root(os.path.realpath(foo))

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20080829/2750cfb2/attachment-0001.sig>


More information about the Python-list mailing list