W3Basic Logo

Python String isspace() Method

The str.isspace() method in Python is a string method that returns True if all characters in a string are whitespace characters and False otherwise.

A whitespace character is a character that represents a space, tab, or line break in a string. Some examples of whitespace characters are space (' '), tab ('\t'), and newline ('\n').

Example:

text = ' '
print(text.isspace())

Output

True

Syntax

The Syntax of the str.isspace() function is:

str.isspace()

Here, str is a string.

Parameters

The str.isspace() function takes no parameters.

Return Value

The str.isspace() function returns:

  • True if the string contains only whitespace characters
  • False if the string has at least one character that is not whitespace or an empty string.

Example 1: Demonstration of isspace() method in Python

The isspace() method will only return True if all characters in the string are whitespace characters. The whitespace character can be a tab, space, new line, etc., as shown in the example below.

# string with empty space
text = ' '
print(text.isspace())

# string with multiple empty spaces
text = '       '
print(text.isspace())

# string with tab character
text = '\t'
print(text.isspace())

# string with newline character
text = '\n'
print(text.isspace())

Output

True
True
True
True

Example 2: How to use isspace() method in real program?

def check_isspace(text):
    if (text.isspace()):
        return "String contains only whitespaces"
    else:
        return "String contains non-whitespace characters"


print(check_isspace("\r\t"))
print(check_isspace("Hello \t"))

Output

String contains only whitespaces
String contains non-whitespace characters

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: