Python string isspace() method is a built-in function that returns True if all the characters in a string are whitespace characters. Otherwise, it returns false.
What are whitespace characters in Python?
Characters that are used for spacing are called whitespace characters. For example tabs, spaces, newlines, etc.
The isspace()
function is used to check if the argument contains all whitespace characters such as:
- ”– Space
- ‘\t’ – Horizontal tab
- ‘\n’ – Newline
- ‘\v’ – Vertical tab
- ‘\f’ – Feed
- ‘\r’ – Carriage return
Syntax
The syntax of isspace() method is:
string.isspace()
Parameters
The isspace()
method doesn’t take any parameters.
Return value
The isspace()
method returns:
- True if all characters in the string are whitespace characters
- False if the string is empty or contains at least one or more non-whitespace character
Example 1: Working with isspace() method
# whitespace characters. returns true
text1 = "\t "
print(text1.isspace())
# string contains non whitespace
text2= "Hello World"
print(text2.isspace())
# whitespace and returns true
text3= " "
print(text3.isspace())
# empty string and returns false
text4=""
print(text4.isspace())
# whitespace characters returns false
text5= "\t\n\f"
print(text5.isspace())
Output
True
False
True
False
True
Example 2: Program to check if the string has only whitespace characters
# whitespace string
text1 = "\t\n\f"
if(text1.isspace()):
print("String contains only whitespace characters")
else:
print("String contains non whitespace characters")
# Non whitespace String
text2= " \t Hello"
if(text2.isspace()):
print("String contains only whitespace characters")
else:
print("String contains non whitespace characters")
Output
String contains only whitespace characters
String contains non whitespace characters