开发者

How to detect lines with only a white space in a text?

开发者 https://www.devze.com 2023-03-11 03:16 出处:网络
Given that \"empty line\" is a white space: I am trying to read a text file line by line. I want to ignore whitespace lines. Or in a more correct way, I want to detect empty lines.

Given that "empty line" is a white space:

I am trying to read a text file line by line. I want to ignore whitespace lines. Or in a more correct way, I want to detect empty lines.

An empty line can contain spaces, newline characters, etc. And it is still considered as an empty line. If you open it up in notepad, in an empty line you should not see anything.

Is there a quick way of doing this in Python? I am new to pytho开发者_StackOverflow社区n by the way.


for line in someopenfile:
  if line.isspace():
    empty_line()


Using strip() on any string returns a string with all leading and trailing whitespace stripped. So calling that on a line with only whitespace gives you an empty string. You can then just filter on strings with non-zero length.

>>> lines=['   ','abc','']
>>> print filter(lambda x:len(x.strip()),lines)
['abc']
>>>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号