Python isspace() Method | .com
Python isspace() Method
The isspace() method checks whether all characters in the string are whitespace characters (including spaces, tabs, newlines, etc.), and returns True if so, otherwise False.
Syntax
str.isspace()
Parameters
No parameters required.
Returns
Returns True if all characters in the string are whitespace characters; otherwise, returns False.
Example
# Example 1: String with only whitespace
text1 = " "
print(text1.isspace()) # Output: True
# Example 2: String with non-whitespace characters
text2 = " hello "
print(text2.isspace()) # Output: False
# Example 3: Empty string
text3 = ""
print(text3.isspace()) # Output: False
# Example 4: String with tab and newline
text4 = "tn"
print(text4.isspace()) # Output: True
Notes
- Whitespace characters include space (
' '), tab ('t'), newline ('n'), carriage return ('r'), form feed ('f'), and vertical tab ('v'). - An empty string returns
Falsebecause it contains no characters at all. - This method is useful for validating input data to check if a string is purely whitespace or empty.
Related Methods
isalnum()β Checks if all characters are alphanumeric.isalpha()β Checks if all characters are alphabetic.isdigit()β Checks if all characters are digits.islower()β Checks if all characters are lowercase.isupper()β Checks if all characters are uppercase.
Tip: Use
isspace() when you want to verify that a string contains only whitespace or is completely empty.
YouTip