How to detect strings that contain only whitespaces in Python
To check if a string is containing only white spaces or not you can use the isspace()
method in Python. This tutorial is to show you how to detect strings that contain only whitespaces in Python.
To differentiate between an empty string and a string that contains only whitespace or whitespaces you can use this method too.
Also, you can differentiate between a null string and a whitespace string using this isspace()
method.
Here are a few examples of strings:
"hi whatsup?" // only whitespaces? NO " " // only whitespaces? YES "" // only whitespaces? NO
Null or empty strings are not containing whitespaces in them.
The isspace() method in Python will only check if the string is only containing whitespaces in it and nothing else.
Detect strings that contain only whitespaces in Python
Here is a code snippet come example to make it simple to understand:
first_string = "whatsup" second_string = " " third_string = "" print(first_string.isspace()) print(second_string.isspace()) print(third_string.isspace())
The output of this Python program is given below:
False True False
From the above program and its output, you can see the isspace()
method returns a value either true or false. In the case of an empty or null string, it will return false. If the string contains only whitespaces then it is the only situation when it returns true.
You can see in the above example I have created three strings.
Then checked those strings with isspace()
method.
first_string
is not satisfying the condition to return true. So it will return false.
second_string
only contains whitespaces in it. So it will return true.
third_string
is an empty string so it is also unable to satisfy the condition to return true. So it will return false.
You may also read,
Leave a Reply