Check if string contains only whitespace
To rapidly confirm if a string consists entirely of whitespace characters, use the isspace()
method:
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:
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:
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:
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:
This spits out a list of boolean values resulting from the whitespace check for each string.
Was this article helpful?