deleting the first and the last character of a string

Peter Hansen peter at engcorp.com
Wed Sep 11 08:33:06 EDT 2002


Padraig Brady wrote:
> Manuel Hendel wrote:
> 
>> Is there anything which says delete the first or last
>> character of a string? 
[snip]
>> for line in inputfile.readlines():
>>         fields = string.split(line, "|")
>>         lineN = string.join(fields[1:-1], "|")
>>
>> Isn't there any better solution? ;-)
>>
> How about: line = line[1:-1]

Which doesn't quite work as-is for the OP, since he's using readlines()
to bring in the lines and this will delete only the trailing newline,
not the final | character.  The basic idea is sound though, but
susceptible to problems if there is any leading or trailing whitespace
as well.  The OP didn't specify whether that was possible.

-Peter




More information about the Python-list mailing list