I have a sequence file begining with >
and afterwards a lot of letters followed by newlines and then again >
. I am able to extract the line begining with >
and the letter lines in to two different variables, when there are no newlines, but I does not work if there are any newlines. My question is, how can I, in my script, remove these newlines?
Asked
Active
Viewed 1,670 times
2

GIZ
- 4,409
- 1
- 24
- 43
3 Answers
3
Your question's pretty unclear, but if you simply need to remove all newlines, use str.replace
(replace("\n", "")
)

Daniel
- 769
- 8
- 21
2
If you have a string 'blah'
containing newlines:
# Replaces all newline characters with nothing
blah = blah.replace("\n", "")
PS: Once you have found an answer which works for you, click the tick next to the answer to 'accept' it (helping others with your problem know which solution works).

Adi219
- 4,712
- 2
- 20
- 43
0
Depends on exactly what you're trying to do.
You can always replace any sequence in a string by using replace
. In this case you'd do something like
foo.replace("\n", "")
If you're just trying to remove the newline from the end of a bunch of lines, you're better off using strip
.
foo.strip()
What you probably want to do is this:
with open(file_path, "r") as fh:
lines = [line.strip() for line in fh.readlines()[1:-1]]
That will open the file, then read each line (without the newline) into the variable lines
, and ignore the first and last lines.

Batman
- 8,571
- 7
- 41
- 80
-
I do it like: file = open('somefile', 'r') for line in file: line = line.rstrip() I have also tried with replace, but they do not work for me. I still have problems. – Aug 12 '17 at 13:35