Search code examples
pythonstringtrailing

How to remove final character in a number of strings?


I have a number of strings that I would like to remove the last character of each string. When I try out the code below it removes my second line of string instead of removing the last element. Below is my code:

Code

with open('test.txt') as file:
    seqs=file.read().splitlines()
    seqs=seqs[:-1]

test.txt

ABCABC
XYZXYZ

Output

ABCABC

Desired output

ABCAB
XYZXY

Solution

  • Change this seqs=seqs[:-1]

    to a list comprehension:

    seqs=[val[:-1] for val in seqs]
    

    Note:

    • The problem in your old method is that seq is a list of strings i.e ["ABCABC","XYZXYZ"]. You are just getting the item before last item ABCABC which explains the output.
    • What I have done is get the strings from the list and omit it's last character.