rkachach
rkachach

Reputation: 17325

Check if string is None, empty or has spaces only

What's the Pythonic way of checking whether a string is None, empty or has only whitespace (tabs, spaces, etc)? Right now I'm using the following bool check:

s is None or not s.strip()

..but was wondering if there's a more elegant / Pythonic way to perform the same check. It may seem easy but the following are the different issues I found with this:

Upvotes: 8

Views: 11300

Answers (2)

minus one
minus one

Reputation: 805

It is also possibile to do something like the following:

strings = [ None, "  Hello +1 ", "    ", "World", "  +1, +2" ]
for item in strings:
  is_empty = not (item or '').strip()  # <--- takes '' over None
  print(f"item: '{item}' --> is empty: {is_empty}")

# output:
# item: 'None' --> is empty: True
# item: '  Hello  ' --> is empty: False
# item: '    ' --> is empty: True
# item: 'World' --> is empty: False

The accepted answer is possibly better, this solution only has the advantage that it supports other string related functions as well, like:

  size = len( item or '' )
  if (item or '').startswith('hello'):
    print(f"item has: {(item or '').count("+1")}")

This implementation may still fail if the item is not None and not string, eg. integer, ...

See also:

Upvotes: 0

Tomerikoo
Tomerikoo

Reputation: 19395

The only difference I can see is doing:

not s or not s.strip()

This has a little benefit over your original way that not s will short-circuit for both None and an empty string. Then not s.strip() will finish off for only spaces.

Your s is None will only short-circuit for None obviously and then not s.strip() will check for empty or only spaces.

Upvotes: 12

Related Questions