deleting the first and the last character of a string

Andrew Henshaw andrew.henshaw at
Wed Sep 11 14:34:42 CEST 2002

Manuel Hendel wrote:

> I got a file with fields seperated by a "|". The problem is that there
> is also a "|" at the beginning and at the end of each line although
> there no fields in front or behind these "|". Now I want to delete
> these two "|". 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.
> I solved it like this, but I honestly don't like it that way.
> #!/usr/bin/env python
> #
> import sys
> import string
> inputfile = open(sys.argv[-1], "r")
> for line in inputfile.readlines():
>         fields = string.split(line, "|")
>         lineN = string.join(fields[1:-1], "|")
> Isn't there any better solution? ;-)
> Manuel

Just like your slicing of the list, you can slice a string:


Although, I believe that each of your strings will have a \n that
needs to be deleted; therefore,


Andrew Henshaw

More information about the Python-list mailing list