简体   繁体   中英

Check if string is None, empty or has spaces only

What's the pythonic way for checking whether a string is None , empty or has only spaces? 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 following are the different issues I found with this:

  • isspace returns False if the string is empty
  • a bool of string which has spaces is True in Python
  • We cannot call any method ( isspace or strip ) on a None object

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM