Python 3 – String isspace() Method
In Python, a string is a sequence of characters enclosed in quotes. The isspace() method is a built-in function in Python 3 that returns True if all the characters in a string are whitespace characters, i.e., spaces, tabs, newlines, etc. Otherwise, it returns False.
The method has the following syntax:
string.isspace()
Here, string
is the string to be checked for whitespace characters.
Examples
Let’s see some examples to understand it better:
Example 1
sentence = "Hello World"
print(sentence.isspace())
Output:
False
Explanation:
The above code checks whether the sentence
string contains all whitespace characters. As the string Hello World
contains non-space characters, the output of the isspace() method is False
.
Example 2
sentence = " "
print(sentence.isspace())
Output:
True
Explanation:
The above code checks whether the sentence
string contains all whitespace characters. As the string has only spaces, the output of isspace() method is True
.
Using the isspace() method in conditions
The isspace() method can be particularly useful when working with user input data. For instance, if the user is required to enter a password, we can use the isspace() method to verify if the input string contains only whitespace characters.
Here is an example:
password = input("Enter your password: ")
if password.isspace():
print("Your password cannot contain only whitespace characters.")
else:
print("Your password is valid.")
In the code above, if the user enters only whitespace characters, the output will be Your password cannot contain only whitespace characters.
Otherwise, the output will be Your password is valid.
.
Using isspace() method with loops
We can also use the isspace() method with loops, particularly to count the number of whitespace characters in a string. Here is how you can achieve this:
sentence = "Hello world! "
count = 0
for char in sentence:
if char.isspace():
count += 1
print(f"The number of whitespace characters in the sentence is: {count}")
In the code above, the for loop iterates through the sentence
string, and if the current character is a whitespace character, it increments the count variable. At the end of the loop, the number of whitespace characters in the string is displayed.
Output:
The number of whitespace characters in the sentence is: 1
Conclusion
The isspace() method is a useful tool in Python that can be used to validate user input data, count whitespace characters in a string, and much more. We hope you have found this tutorial helpful in understanding this method.