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 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 contain only whitespace or whitespaces you can use this method too.
Also, you can differentiate between a null string and 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 it.
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:
False True False
So you can see isspace() method returns a value either true or false. In the case of empty or null string it will return false. If the string contains only whitespaces in then only it will return true.
You can see the above example I have created three strings.
Then checked those string 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,
- How to remove null values from list in Python
- how to escape quotes in python – escape quotes from string