Python String isspace() Method – Tutorial with Examples

Python String isspace() Method

In Python, a string is a sequence of characters. The isspace() method is a built-in method that can be used to check whether a given string contains only whitespace characters. A whitespace character is any character that is considered whitespace, such as a space, tab, or newline.

Syntax

The syntax of the isspace() method is as follows:

string.isspace()

Here, string is the string that we want to check for whitespace characters.

Return Value

The isspace() method returns True if all the characters in the string are whitespace characters. Otherwise, it returns False.

Examples

Here are three different examples of how to use the isspace() method in Python:

Example 1: Checking if a String Contains Only Whitespace Characters

The following example demonstrates how to use the isspace() method to check if a given string contains only whitespace characters:

string = "   \t\n"
result = string.isspace()
print(result)

Output:

True

In this example, we define a string that contains only whitespace characters and use the isspace() method to check if it contains only whitespace characters. Since the string contains only whitespace characters, the method returns True.

Example 2: Checking if a String Contains Non-Whitespace Characters

The following example demonstrates how to use the isspace() method to check if a given string contains non-whitespace characters:

string = "  Hello World!  "
result = string.isspace()
print(result)

Output:

False

In this example, we define a string that contains non-whitespace characters and use the isspace() method to check if it contains only whitespace characters. Since the string contains non-whitespace characters, the method returns False.

Example 3: Removing Whitespace Characters from a String

The following example demonstrates how to use the isspace() method to remove whitespace characters from a given string:

string = "  Hello World!  "
result = "".join(c for c in string if not c.isspace())
print(result)

Output:

HelloWorld!

In this example, we define a string that contains whitespace characters and use the isspace() method along with a generator expression to remove all whitespace characters from the string. The resulting string contains only the non-whitespace characters.

Use Cases

The isspace() method can be useful in a variety of scenarios, such as:

  • Validating user input to ensure that it only contains whitespace characters
  • Removing whitespace characters from a string
  • Checking if a string contains only whitespace characters before performing a specific operation on the string

Leave a Reply

Your email address will not be published. Required fields are marked *