John Manak
John Manak

Reputation: 13558

Testing string content on non-whitespace

I want to test if a sentence contains anything else than white-space characters. This is what I use currently:

if len(teststring.split()) > 0:
    # contains something else than white space
else:
   # only white space

Is this good enough? Are there any better ways of doing it?

Upvotes: 4

Views: 9698

Answers (4)

lvc
lvc

Reputation: 35089

Strings have a method called str.isspace which, according to the docs:

Return[s] true if there are only whitespace characters in the string and there is at least one character, false otherwise.

So, that means:

if teststring.isspace():
    # contains only whitespace

Will do what you want.

Upvotes: 14

Levon
Levon

Reputation: 143122

I would use the strip() function for this purpose.

  if teststring.strip():
      # non blank line
  else:
      # blank line

Upvotes: 7

monkut
monkut

Reputation: 43870

You can just use .strip().

Your resulting string will be empty if it is only whitespace.

if teststring.strip():
    # has something other than whitespace.
else:
    # only whitespace

Or perhaps more explicitly as JBernardo pointed out:

if not teststring.isspace():
    # has something other than whitespace

else:
    # only whitespace.

Upvotes: 2

dave
dave

Reputation: 12806

 if teststring.split():
      print "not only whitespace!" 
 else:
     print ":("

Upvotes: 1

Related Questions