Python String isspace() Method
Last Updated :
02 Jan, 2025
Improve
isspace()
method in Python is used to check if all characters in a string are whitespace characters. This includes spaces (' '
), tabs (\t
), newlines (\n
), and other Unicode-defined whitespace characters. This method is particularly helpful when validating input or processing text to ensure that it contains only whitespace characters.
Let's understand this with the help of an example:
s = " "
print(s.isspace())
Output
True
Explanation:
- The string
" "
contains only whitespace characters (spaces). - The
isspace()
method returnsTrue
since all characters in the string are whitespace.
Table of Content
Syntax of isspace() method
string.isspace()
Parameters
- The isspace() method does not take any parameters.
Return Type
- Returns
True
if all characters in the string are whitespace. - Returns
False
if the string contains one or more non-whitespace characters or is empty.
String with mixed characters
Let's see what happens when the string contains non-whitespace characters:
s = "Python is fun! "
print(s.isspace())
Output
False
Explanation:
- The string contains non-whitespace characters (
"Python is fun!"
). - The presence of these characters causes the method to return
False
.
String with tabs and newlines
isspace()
method considers tabs and newlines as whitespace characters:
s = "\t\n"
print(s.isspace())
Output
True
Explanation:
- The string contains only a tab (
\t
) and a newline (\n
), both of which are valid whitespace characters. - The method returns
True
.
What happens when the string is empty?
An empty string does not contain any characters, including whitespace.
s = ""
print(s.isspace())
Output
False
Explanation:
- The method returns False.