Check if string contains only whitespace
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 Question
00:26 Accepted answer (Score 401)
01:09 Answer 2 (Score 73)
01:34 Answer 3 (Score 38)
02:02 Answer 4 (Score 26)
02:14 Thank you
--
Full question
https://stackoverflow.com/questions/2405...
Accepted answer links:
[str.isspace()]: https://docs.python.org/3/library/stdtyp...
[unicodedata]: https://docs.python.org/3/library/unicod...
[str.strip()]: https://docs.python.org/3/library/stdtyp...
Answer 2 links:
[str.isspace()]: https://docs.python.org/3/library/stdtyp...
Answer 3 links:
[isspace()]: https://docs.python.org/2/library/stdtyp...
Answer 4 links:
[str.isspace()]: https://docs.python.org/3/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #text #whitespace
#avk47
ACCEPTED ANSWER
Score 426
Use the str.isspace() method:
Return
Trueif there are only whitespace characters in the string and there is at least one character,Falseotherwise.A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.
Combine that with a special case for handling the empty string.
Alternatively, you could use str.strip() and check if the result is empty.
ANSWER 2
Score 81
str.isspace() returns False for a valid and empty string
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
Therefore, checking with not will also evaluate None Type and '' or "" (empty string)
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
ANSWER 3
Score 39
You want to use the isspace() method
str.isspace()
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
That's defined on every string object. Here it is an usage example for your specific use case:
if aStr and (not aStr.isspace()):
print aStr
ANSWER 4
Score 26
You can use the str.isspace() method.