简体   繁体   中英

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

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 ie ["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.
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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM