[python] Check if string contains only whitespace

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)

This question is related to python text whitespace

The answer is


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


You can use the str.isspace() method.


I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

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]

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.


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

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")

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)

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"

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to whitespace

How to create string with multiple spaces in JavaScript git: fatal: I don't handle protocol '??http' Show whitespace characters in Visual Studio Code What is the symbol for whitespace in C? How to print variables without spaces between values Trim whitespace from a String How do I escape spaces in path for scp copy in Linux? Avoid line break between html elements Remove "whitespace" between div element How to remove all white spaces in java