Check for new line character?

Erik Max Francis max at alcyone.com
Sun Oct 26 19:12:32 EST 2003


Yazar Yolait wrote:

> I want to skip lines in a file that are blank and that start with "&".
> So I
> strip(None) them and then startswith("&") but the only problem is if
> the
> line has nothing but white space and I strip(None) it then it contains
> nothing but a new line character right?

No, the newline character is whitespace as well so you'll be left with
the empty string:

>>> '   \n'.strip()
''
>>> '&\n'.strip()
'&'

> So how do I  check if the
> line
> contains a new line character?  I can no longer use isspace().

Pretty basic:

	while True:
	    line = inputFile.readline()
	    if not line:
	        break
	    line = line.strip()
	    if not line or line.startswith('&'):
	        continue
	    ...

If the rest of your program is sensitive to (non-newline) whitespace,
then just strip the newline, change

	line = line.strip()

to

	if line[-1] == '\n':
	    line = line[:-1]

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ To endure what is unendurable is true endurance.
\__/  (a Japanese proverb)




More information about the Python-list mailing list