deleting the first and the last character of a string

Cliff Wells LogiplexSoftware at earthlink.net
Wed Sep 11 16:50:07 EDT 2002


On Wed, 2002-09-11 at 12:46, Sean 'Shaleh' Perry wrote:
> On Wednesday 11 September 2002 12:25, Markus wrote:
> > Sean 'Shaleh' Perry wrote:
> > >> Is there anything which says delete the first or last
> > >> character of a string? I checked the string module on the web, but I
> > >> couldn't find anything.
> > >>
> > >>>> s = '|f|o|o|'
> > >>>> s.strip('|')
> > >>>
> > >>> s[1:-1]
> >
> > 'f|o|o'
> >
> > -Markus
> 
> True, but I like that the strip() call handles the case where one of the 
> delimiters is missing.  One of the bugs that always bit me in perl was using 
> chop() to eat the newline character when there was not a newline there to 
> eat.  I try to avoid putting myself in that situation now.

Let me apologize in advance for this:

>>> def chopd(s, d):
...     s = s.strip()
...     return s[s[0] == d : {0:len(s), 1:-1}[s[-1] == d]]
... 
>>> chopd("|f|o|o|", '|')
'f|o|o'
>>> chopd("|f|o|o", '|')
'f|o|o'
>>> chopd("f|o|o|", '|')
'f|o|o'
>>> chopd("f|o|o", '|')
'f|o|o'
>>> 

Of course, since you are worried about missing delimiters, you also have
to consider whether the data being delimited contains whitespace
(strip() might then remove some of the data).

Have you considered using one of the many delimited-file handling
modules that already exist?

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list