Explain Codes LogoExplain Codes Logo

Check if string contains only whitespace

python
functions
best-practices
collections
Anton ShumikhinbyAnton Shumikhin·Oct 4, 2024
TLDR

To rapidly confirm if a string consists entirely of whitespace characters, use the isspace() method:

result = your_string.isspace() # Returns True when your string is a peaceful, whitespace-only zen garden

If result is True, congrats, your string is filled only with the serene beauty of whitespace. False? Well, prepare to sort through your textual jungle.

Comprehensive check: including emptiness

The provided solution works great for a string full of diverse whitespace characters. But what about the one that arrives with nothing at all - an empty string? That's the tricky bit as isspace() would return False for an empty string. Here's a more comprehensive version of the function:

def is_only_whitespace(s): return s.isspace() or not s # "Nothingness can be full of answers," whispered the philosophical python code.

This function gracefully handles empty strings in addition to the regular whitespace strings.

The stripping alternative

Sometimes, it's not about what you have, but what you can lose. If you want to take an alternative route, use the powerful strip() method and see what's left:

result = not your_string.strip() # If after the strip-tease nothing is left, it was probably all spaces to begin with 😉.

This strip() and not combo returns True if your string, after undergoing the stripping operation, turns up naked (i.e., empty). This implies it was only padded with whitespace characters initially.

Robust coding: empty or whitespace

Occasionally you might want to check if a string is either empty or composed solely of whitespace characters. This function does that magic:

def is_empty_or_whitespace(s): return not s or s.isspace() # Just like a good librarian, we make sure it's either quiet or non-existent.

Not only spaces: A tryst with Unicode

The world of Unicode is vast and wondrous. Tab \t, newlines \n, carriage returns \r, and various other exotic characters fall under the umbrella of whitespace too. Fear not! isspace() is a savvy globetrotter - it recognizes all of them.

Mass check: dealing with multiple strings

What if you have a gaggle of strings to check? Don't fear, Python magic provides an elegant solution:

strings = [" ", " text ", "\t\n", ""] only_whitespace = [s.isspace() or not s for s in strings] # Like a boss, tackling multiple strings at once! 🚀

This spits out a list of boolean values resulting from the whitespace check for each string.