The isspace()
method in Python is used to check whether a string contains only whitespace characters. It returns True
if all characters in the string are whitespace characters (spaces, tabs, newlines, etc.), and there is at least one character in the string. Otherwise, it returns False
.Here's the syntax of the isspace()
method:
string.isspace()
# Examples of isspace() method
string1 = " "
string2 = " Hello "
string3 = "\t\t\t"
string4 = "\n"
string5 = ""
result1 = string1.isspace()
result2 = string2.isspace()
result3 = string3.isspace()
result4 = string4.isspace()
result5 = string5.isspace()
print("String 1:", string1)
print("String 2:", string2)
print("String 3:", string3)
print("String 4:", string4)
print("String 5:", string5)
print("isspace() result for String 1:", result1)
print("isspace() result for String 2:", result2)
print("isspace() result for String 3:", result3)
print("isspace() result for String 4:", result4)
print("isspace() result for String 5:", result5)
String 1:
String 2: Hello
String 3:
String 4:
String 5:
isspace() result for String 1: True
isspace() result for String 2: False
isspace() result for String 3: True
isspace() result for String 4: True
isspace() result for String 5: False
In this example, string1
, string3
, and string4
contain only whitespace characters, so isspace()
returns True
for these strings. string2
contains non-whitespace characters along with whitespace characters, so isspace()
returns False
for string2
. string5
is an empty string, and since it has no characters, isspace()
still returns False
.
The isspace()
method is useful when you want to check whether a string contains only whitespace characters or when you need to validate user input for whitespace-only strings. It can be helpful for handling formatting and cleaning input data.