3

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
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
Xiong89
  • 767
  • 2
  • 13
  • 24
  • 2
    Think about what `seqs` is after the first assignment... It's a list of all *lines* (i.e. a list of strings). You need another loop to modify each line. List comprehension will be your friend in this situation. – Some programmer dude Jan 12 '16 at 09:39
  • You are dealing with array of arrays of strings, not arrays of strings – Rocketq Jan 12 '16 at 09:39

4 Answers4

10

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.
d e
  • 13
  • 2
The6thSense
  • 8,103
  • 8
  • 31
  • 65
5
with open('test.txt') as file:
    for seq in file:
        print seq.strip()[:-1]

This iterates through every line in the file and prints the line omitting the last character

Kaustav Datta
  • 403
  • 2
  • 9
4

file.read().splitlines() returns a list. Therefore the following could solve your problem:

enter with open('test.txt') as file:
    data = list(map(lambda x: x[:-1], file.read().splitlines()))

Then you can join the list back into a string: "\n".join(data)

Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26
2

seqs is a list of lines. You need to loop through the lines to access each line:

with open('test.txt') as file:
    seq = file.read().splitlines()
    for word in seq:
        word = word[:-1]
        print word
Idos
  • 15,053
  • 14
  • 60
  • 75
deborah-digges
  • 1,165
  • 11
  • 19