The isspace() method in Python is a built-in string method used to check whether a string consists of only whitespace characters.
Syntax:
string.isspace()
How to use the isspace() method:
string1 = " " # contains only spaces
print(string1.isspace()) # Output: True
string2 = "Hello World"
print(string2.isspace()) # Output: False
string3 = "\t\t"
print(string3.isspace()) # Output: True
string4 = "This is not empty."
print(string4.isspace()) # Output: False
Example 1
Removing Leading and Trailing Whitespace.
text = " Hello, World! "
cleaned_text = text.strip() # Removes leading and trailing whitespace
print(cleaned_text) # Output: "Hello, World!"
Example 2
Checking string whitespace characters.
text = " Hello World! "
if text.isspace():
print("The string contains only whitespace characters.")
else:
print("The string contains non-whitespace characters.")