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:
seq
is a list of strings ie ["ABCABC","XYZXYZ"]
. You are just getting the item before last item ABCABC
which explains the output.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.