2

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:

  • isspace() returns False if the string is empty.
  • A bool of string that has spaces is True in Python.
  • We cannot call any method, such as isspace() or strip(), on a None object.
wovano
  • 4,543
  • 5
  • 22
  • 49
rkachach
  • 16,517
  • 6
  • 42
  • 66

1 Answers1

4

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • One possible improvement could be doing `set(s)!={" "}` instead of `not s.strip()`, but that's getting a bit bikesheddy – 0x263A Jul 19 '22 at 13:48