Check if string contains only whitespace

PythonTextWhitespace

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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]

Solution 3 - Python

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

Solution 4 - Python

You can use the str.isspace() method.

Solution 5 - Python

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"

Solution 6 - Python

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

Solution 7 - Python

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.

Solution 8 - Python

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

Solution 9 - Python

I used following:

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

Solution 10 - Python

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

Solution 11 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbodacydoView Question on Stackoverflow
Solution 1 - PythonVladislavView Answer on Stackoverflow
Solution 2 - PythonJohn MachinView Answer on Stackoverflow
Solution 3 - PythonEricView Answer on Stackoverflow
Solution 4 - PythonSilentGhostView Answer on Stackoverflow
Solution 5 - PythonkommradHomerView Answer on Stackoverflow
Solution 6 - PythonBhavesh MunotView Answer on Stackoverflow
Solution 7 - PythonfralauView Answer on Stackoverflow
Solution 8 - PythonJames WierzbaView Answer on Stackoverflow
Solution 9 - PythonEmdadul SawonView Answer on Stackoverflow
Solution 10 - PythonbroadbandView Answer on Stackoverflow
Solution 11 - PythonAhmedView Answer on Stackoverflow