How to check if the string is empty in Python?

To check if a string is empty in Python, you can use the following approaches depending on your needs:

1. Check for a Strictly Empty String

An empty string has no characters (len == 0).
Example: ""

my_str = ""

# Method 1: Check truthiness (Pythonic)
if not my_str:
    print("String is empty")

# Method 2: Explicit length check
if len(my_str) == 0:
    print("String is empty")

2. Check for “Blank” Strings (Empty or Whitespace)

A blank string contains only whitespace characters (e.g., " ").
Example: " "

my_str = "    "

# Use .strip() to remove whitespace and check emptiness
if not my_str.strip():
    print("String is empty or contains only whitespace")

3. Handle Edge Cases (None or Non-Strings)

If your variable might be None or a non-string type:

value = None  # or 123, [], etc.

# Check if the value is a string and then validate
if isinstance(value, str) and not value.strip():
    print("Valid empty/blank string")
else:
    print("Not a string or not empty")

Summary Table

CaseCode
Empty string ("")if not my_str:
Whitespace-only (" ")if not my_str.strip():
Edge cases (None, non-strings)isinstance(my_str, str) and ...

Examples in Action

def is_empty_or_blank(s):
    return isinstance(s, str) and (not s.strip())

print(is_empty_or_blank(""))        # True
print(is_empty_or_blank("   "))     # True
print(is_empty_or_blank("Hello"))   # False
print(is_empty_or_blank(None))      # False (not a string)

Key Takeaways

  • Use if not my_str for basic empty-string checks.
  • Use .strip() to handle strings with only whitespace.
  • Guard against None or non-string types with isinstance() if needed.

Leave a Reply

Your email address will not be published. Required fields are marked *