How to guard against nulls in python
In python, how do I check if a string is either null or empty?
In c# we have String.IsNullOrEmpty(some_string)
开发者_JAVA百科Also, I'm doing some regex like:
p = re.compile(...)
a = p.search(..).group(1)
This will break if group doesn't have something at index 1, how do guard against this ? i.e. how would you re-write those 2 lines safely?
Just check for it. Explicit is better than implicit, and one more line won't kill you.
a = p.search(...)
if a is not None:
# ...
The typical way with re module is:
m = p.search(..)
if m:
a = m.group(1)
or
m = p.search(..)
a = m.group(1) if m else ''
Unfortunately (or fortunately), Python does not allow you to write everything in one line.
p.search(..) will return None, if nothing was found, so you can do:
a = p.search(..)
if a is None:
# oops
print "Nothing found"
else:
print "Hooray!"
By "null or empty" I suppose you mean None
or ""
. Luckily, in python both of these evaluate to False
.
If your C# looks like this:
if (! String.IsNullOrEmpty(some_string))
do_something();
Then your Python would look like this:
if not some_string:
do_something()
This might be incorrect but I think you can use if p != None (or it might be null/NULL)
精彩评论