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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With