Skip to content

script_15.py - String Emptiness Checker

Code

Python
#!/usr/bin/env python3
"""String emptiness checker"""

text = input("Enter some text (or press enter): ")

if not text:
    print("You entered an empty string")
elif text.strip():
    print(f"You entered: '{text}'")
else:
    print("You entered only whitespace")

Explanation

Line 4: text = input("Enter some text (or press enter): ") - input() returns string type (str) - If user presses Enter without typing, returns empty string "" - text variable stores the string (can be empty)

Line 6: if not text: - not is a logical operator that inverts boolean value - Empty string "" is "falsy" in Python (evaluates to False in boolean context) - not "" becomes not False which is True - Non-empty strings are "truthy" (evaluate to True) - not "hello" becomes not True which is False - This checks if string is completely empty (length 0)

Line 8: elif text.strip(): - .strip() is a string method that removes whitespace from both ends - Returns a new string without leading/trailing spaces, tabs, newlines - Example: " hello ".strip() returns "hello" - Example: " ".strip() returns "" - Used in boolean context (truthy/falsy) - True if string has content after removing whitespace - False if string becomes empty after stripping

Line 10: else: - Executed when text is not empty (line 6 False) AND text.strip() is empty (line 8 False) - Means original string had content, but only whitespace characters - Examples: " ", "\t", "\n", " \t\n "