Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.IsNullOrWhiteSpace equivalent in python

Tags:

python

I am new to python and wanted to find the equivalent of C# string.IsNullOrWhiteSpace in python. With my limited web search, I created the below function

def isNullOrWhiteSpace(str):
  return not str or not str.strip()  

print "Result: " + isNullOrWhiteSpace("Test")
print "Result: " + isNullOrWhiteSpace(" ")
#print "Result: " + isNullOrWhiteSpace() #getting TypeError: Cannot read property 'mp$length' of undefined

But this is printing

Result: undefined
Result: undefined

I wanted to try how it would behave if no value is passed. Unfortunately, I am getting TypeError: Cannot read property 'mp$length' of undefined for the commented line. Can someone help with these situations I need to handle?

like image 503
user007 Avatar asked Jun 09 '26 00:06

user007


1 Answers

You can do the follwoing using isspace:

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

str.isspace()

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

An empty function call is not like passing None to it, so you can set a default value for this specific case.

In your case something like:

def isNullOrWhiteSpace(str=None):
  return not str or str.isspace()

print("Result: ", isNullOrWhiteSpace("Test"))  #False
print("Result: ", isNullOrWhiteSpace(" "))  #True 
print("Result: ", isNullOrWhiteSpace())  #True
like image 173
David Avatar answered Jun 10 '26 14:06

David