Explain Codes LogoExplain Codes Logo

How to check if the string is empty?

python
empty-string
whitespace
truthiness
Alex KataevbyAlex Kataev·Aug 15, 2024
TLDR

Working with strings in Python? Here's how to check if a string is empty:

if not my_string: print("Empty") else: print("Not empty")

Just substitute my_string with your string. This built-in falsy behavior of empty strings in Python has you covered!

Emptiness and the invisible intruder: whitespaces

Now, not every empty looking string is innocent. You've got the invisible guests: whitespaces. Luckily, it's easy to spot these intruders.

if not my_string.strip(): print("Empty...or full of invisible intruders") else: print("Contains visible characters")

By using str.strip(), you can banish these lurking whitespaces from both ends of your string.

What would Python do? Embracing Pythonic style

Like a Zen master asking, "What's the sound of one hand clapping?" a Pythonista asks, "What's the way of checking an empty string?"

# Python, show me the way empty_string = "" if empty_string: # Should I? print("Wise guy, aren't ya?") else: # So Zen print("That's the Python way!")

Getting explicit: double-checking with an empty string

When in doubt, spell it out! Explicit comparisons leave no room for misunderstanding.

if my_string == "": # I'm watching you 👀 print("Empty, we double-checked")

This literally checks if my_string is an equal to an empty string. Explicit and clear.

Truth or dare: understanding truthiness

In Python, truth extends beyond True and False; nearly everything has a truthiness value.

  • A string that's full of characters? It's True.
  • An empty string? It's False.

This built-in feature has truth value testing to thank for.

Whitespace detectives: using isspace()

Let's put on our detective hats 🕵️‍♀️. If a string is full of whitespace but no characters, it's still 'empty'.

# Detective work on strings just_whitespace = " " if not just_whitespace or just_whitespace.isspace(): # Check-mate! print("You can't fool me, whitespace!") else: print("We've got other characters here!")

Crafting checks with custom functions

Looking to customize your string checks? Try creating a function for it!

# Function that sees through strings def see_through(s): return bool(s and not s.isspace()) # Clever, aren't we? # Putting our function to use if see_through(my_string): print("Aha! Got ya!") else: print("Just empty space here...")

Smoke test: checking against various inputs

Always test your code against different inputs for that confidence boost!

test_strings = ["", " ", "Real words", "\n", "\t", None] for test_str in test_strings: if not test_str or test_str.isspace(): # Let's see what you're made of print(f"Testing: '{test_str}' ")

Time to debug fiction. The function isn't perfect until it triumphs edge cases.