297

How can I test if a string contains only whitespace?

Example strings:

  • " " (space, space, space)

  • " \t \n " (space, tab, space, newline, space)

  • "\n\n\n\t\n" (newline, newline, newline, tab, newline)

AMC
  • 2,642
  • 7
  • 13
  • 35
bodacydo
  • 75,521
  • 93
  • 229
  • 319

11 Answers11

415

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

AMC
  • 2,642
  • 7
  • 13
  • 35
Vladislav
  • 4,806
  • 1
  • 18
  • 15
76

str.isspace() returns False for a valid and empty string

>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]

Therefore, checking with not will also evaluate None Type and '' or "" (empty string)

>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
BenT
  • 3,172
  • 3
  • 18
  • 38
John Machin
  • 81,303
  • 11
  • 141
  • 189
38

You want to use the isspace() method

str.isspace()

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

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Eric
  • 22,183
  • 20
  • 145
  • 196
  • 2
    Is this not the same solution as the current [top and accepted answer](https://stackoverflow.com/a/2405300/11301900) ? – AMC Jun 26 '20 at 20:38
26

You can use the str.isspace() method.

AMC
  • 2,642
  • 7
  • 13
  • 35
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
14

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"
kommradHomer
  • 4,127
  • 5
  • 51
  • 68
6

Check the length of the list given by of split() method.

if len(your_string.split()==0:
     print("yes")

Or Compare output of strip() method with null.

if your_string.strip() == '':
     print("yes")
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Bhavesh Munot
  • 675
  • 1
  • 6
  • 13
  • 1
    There is no reason to split the string, `len()` works on strings. Also, the OP wasn't asking to test for the empty string, but for a string that was all spaces. Your second method isn't bad though. Also, your parens surrounding the conditional aren't needed in python. – NeilK Jun 16 '17 at 21:00
  • 1
    Strangely enough, the first method is actually a good way to check than *none* of the characters are spaces, if you replace `==0` with `==1` – Mad Physicist Mar 09 '18 at 20:03
  • `if len(your_string.split())==0:` --> `if not your_string.split():`, `if your_string.strip() == '':` --> `if not your_string.strip():`. In any case, the first is inferior to the existing solutions, and the second has already been mentioned in other answers. – AMC Jun 26 '20 at 20:41
3

Here is an answer that should work in all cases:

def is_empty(s):
    "Check whether a string is empty"
    return not s or not s.strip()

If the variable is None, it will stop at not sand not evaluate further (since not None == True). Apparently, the strip()method takes care of the usual cases of tab, newline, etc.

fralau
  • 3,279
  • 3
  • 28
  • 41
  • _since `not None == True`_ It's probably clearer to just say `None is False`. Also, `==` shouldn't be used for these comparisons. – AMC Jun 26 '20 at 20:45
3

Resemblence with c# string static method isNullOrWhiteSpace.

def isNullOrWhiteSpace(str):
  """Indicates whether the specified string is null or empty string.
     Returns: True if the str parameter is null, an empty string ("") or contains 
     whitespace. Returns false otherwise."""
  if (str is None) or (str == "") or (str.isspace()):
    return True
  return False

isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("")   -> True
isNullOrWhiteSpace(" ")  -> True
broadband
  • 3,266
  • 6
  • 43
  • 73
2

I'm assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

Note this does not check for None

James Wierzba
  • 16,176
  • 14
  • 79
  • 120
2

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')
Emdadul Sawon
  • 5,730
  • 3
  • 45
  • 48
1

To check if a string is just a spaces or newline

Use this simple code

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)
Prakash Pazhanisamy
  • 997
  • 1
  • 15
  • 25
Ahmed
  • 414
  • 4
  • 3