Python String isspace()
Python String isspace() method
Python String isspace() method is used to check if all characters in the string are whitespace characters and there is at least one character.
Consider that given string is in x.
" \t\n"
Then the return value of x.isspace() is
True
In this tutorial, you will learn the syntax and usage of String isspace() method in Python language.
Syntax of isspace() method
The syntax of String isspace() method in Python is given below.
str.isspace()
Parameters
The isspace() method takes no parameters.
Return value
isspace() method returns a boolean value of True if all characters in the string are whitespace characters, and also there is at least one character in the string, otherwise the method returns False.
Examples
1. Checking if given string all whitespace characters in Python
In this example, we take a string value in variable my_string. We have to check if all characters in the string are all whitespace characters. The string consists of three single spaces, one tab, and one new line.
Call isspace() method on the string my_string and use the returned value as a condition in Python if else statement as shown in the following program.
Since all characters in the string are whitespace characters, isspace() method returns True, and the if-block executes.
Python Program
my_string = " \t\n"
if my_string.isspace():
print('Given string is SPACE.')
else:
print('Given string is NOT SPACE.')
Output
Given string is SPACE.
2. Checking if given string (with some alphabets) is space in Python
In the following program, we take a string value in variable my_string such that some of the characters in the string are alphabets.
Since, not all characters in the string are whitespace characters, isspace() method returns False, and the else-block executes.
Python Program
my_string = " hello \t\n"
if my_string.isspace():
print('Given string is SPACE.')
else:
print('Given string is NOT SPACE.')
Output
Given string is NOT SPACE.
3. Checking if empty string is space in Python
In the following program, we take an empty string in variable my_string, and check the output of isspace() method for this empty string.
Since, there is no at least one character in the string, isspace() method returns False, and the else-block executes.
Python Program
my_string = ""
if my_string.isspace():
print('Given string is SPACE.')
else:
print('Given string is NOT SPACE.')
Output
Given string is NOT SPACE.
Summary
In this tutorial of Python String Methods, we learned about String isspace() method, its syntax, and examples.