Reputation: 1730
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?
Upvotes: 3
Views: 1329
Reputation: 8318
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
Upvotes: 5