-3

I want to remove all of the trailing whitespace from each element in a list, but strip() and rstrip() don't seem to be doing the trick.

Each element in the list looks like this, but with many more lines of nucleotide sequence:

>gi|317176027|dbj|AB558126.1| Apis mellifera shade mRNA, unspliced mRNA of CYP314A1 CTCTCACGTCGGAATTGACGGCCGCCAGTACGGTCCTTGGCTTTTTCCCGGCACTGAATATCGTCGCAGA TTCGTTCATCGAGTTGATCCGTCGTCAAAGAGTCGGATACAAAGTGACAGGTTTCGAAGAGCTCGCCTAT AAAATGGGATTGGAGAGTAAGATTTAACCCCCCTCCCCCCAACTTCAATATAGTTTTATCGATTTTATCC

What I'm trying to do is iterate over each element in the list and return a sequence as a string, however I need to remove all the whitespace from each of the lines in my list elements. I know this should be a pretty simple task, but I can't seem to figure out why my code isn't working.

This (and each commented out version) returns the exact same thing I have above.

for i in genelist:
    j = i.rstrip()
    #j = i.rstrip('\r\n')
    #j = i.strip()
    #j = i.strip('\r\n')
    print(j)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • What is your expected result? Are you wanting to separate each line into individual strings? I think that `i.split('\n')` way be better suited for what you're trying to achieve. – PacketLoss May 20 '21 at 01:22
  • From your input, it looks like each element is a long string with newlines (not just at the end). Strip won't remove those. You may need to split them, but it's not 100% clear from you question what you're starting with. – Mark May 20 '21 at 01:24
  • @Mark I'm starting with a list where each element is a very long string with many \n characters in it. My expected output is that for every element, I return a string with of the element with no \n characters in it. – Madison Hornstein May 20 '21 at 01:30
  • 1
    `rstrip()` only removes whitespace from the _end_ of the string. – John Gordon May 20 '21 at 01:33
  • You can do `i.replace('\n', '')` – Orbital May 20 '21 at 01:35
  • @PacketLoss I want to combine each line into one big string. Maybe it's not clear in my original question, but I'm not iterating over each line here. I'm iterating over a list of strings that each have the same format. I essentially want to return a one stripped string of each element in that list. – Madison Hornstein May 20 '21 at 01:35
  • Try using a debugger. – TomServo May 20 '21 at 01:36
  • @MadisonHornstein Could you edit your answer to include your expected output? – PacketLoss May 20 '21 at 01:36
  • @Orbital Ahh that worked! Thank you! Still befuddled as to why `i.strip('\n')` wasn't working. – Madison Hornstein May 20 '21 at 01:37
  • @MadisonHornstein Did you read the comment from John Gordon? It explains it clearly. `strip()` only removes from the ends, not the middle. – Barmar May 20 '21 at 01:38

1 Answers1

1

You can remove newlines with i.replace('\n', '')

Orbital
  • 565
  • 3
  • 13