-1
input = open("ex3.txt")
DNA = input.read()
DNA2 = "AAAACCCGGT"
print "string=", DNA,"len=", len(DNA)
print "strin2=",DNA2,"len=",len(DNA2)

returns

>string= AAAACCCGGT
>len= 11
>strin2= AAAACCCGGT len= 10

As you can see, the two strings which appear identical have different lengths because when I load the input using input.read() the string ends in Nonetype (edit: actually ends in '\n')

Is there a way to load string input from a textfile without it ending in Nonetype? Or should I just load as is and splice the input like DNA[:-1] assuming .read() will always have Nonetype as the final value?

Thanks for any tips :-D

Edit: I supposed the reason I was confused about Nonetype is because of the error message: "TypeError: cannot concatenate 'str' and 'NoneType' objects" Anyways, calling .rstrip worked great thanks again everyone

  • 2
    `\n` means **newline**, not `None`. – Veedrac Sep 24 '14 at 19:55
  • how do you know that `DNA` ends in a Nonetype? Are you sure it's not just that your file ends in `\n`? – Dan O Sep 24 '14 at 19:55
  • I won't close as duplicate of http://stackoverflow.com/questions/12330522/reading-a-file-without-newlines because there is an important misunderstanding in this post about what `\n` *is*, but it's worth at least reading that link. – Veedrac Sep 24 '14 at 20:00
  • Try `print repr(DNA), repr(DNA2)` to see what's actually in each of them. There is no such thing as `Nonetype` character. – martineau Sep 24 '14 at 20:09
  • OK, thanks everyone. print repr(DNA) shoes that my string did in fact end in a newline which was showing up as a blank char with type ='str'. I've added .rstrip() as the proper way to handle this. – Dan Vanatta Sep 24 '14 at 21:35

1 Answers1

1

.read on files in text mode will always \n iff there is a return character. This means that DNA[:-1] can break if the line does not have another line after it.

One way to do what you want is DNA.rstrip(). This removes whitespace to the right of the string.

Also, you probably want .readline if you know you want to read a line. read reads the whole file, which may be several lines.

Veedrac
  • 58,273
  • 15
  • 112
  • 169