Blankman
Blankman

Reputation: 266900

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)

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?

Upvotes: 1

Views: 3370

Answers (5)

Wieland
Wieland

Reputation: 1681

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

Upvotes: 1

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

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

Upvotes: 0

Lie Ryan
Lie Ryan

Reputation: 64827

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.

Upvotes: 2

Cat Plus Plus
Cat Plus Plus

Reputation: 129754

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:
    # ...

Upvotes: 5

Chris
Chris

Reputation: 515

This might be incorrect but I think you can use if p != None (or it might be null/NULL)

Upvotes: -2

Related Questions