Python check if string is empty or whitespace | Example code

You can check if the string is empty or whitespace using an isspace() function and strip() function in python.

You can also just use not string with if-else condition statement.

Check if the string is “whitespace” in Python

First, check if the string contains whitespace only or not by using a “isspace() function” in python.

A function returns true if any space and no charter in the string text else it will return false.

# string only space
str1 = " "
print(str1.isspace())

# string without space
str2 = ""
print(str2.isspace())

Output:

True
False

Read more: isspace Python function example

Check if the string is “Empty” in Python

Empty strings are “falsy” which means they are considered false in a Boolean context, so you can just use not string.  

Here’s a function to check if a string is empty:

def is_empty(string):
	return not string.strip()

Example:

str1 = ""
if not str1:
    print("Empty String!")

Output: Empty String!

If you consider whitespace also not in an empty string then use the strip() method, where the strip() method will remove all white space. So if there is only white space then the string becomes empty.

str1 = "  "
if not str1.strip():
    print("Empty String!")

Q: How to get a number of spaces in a string in Python?

Answer: Use the count() function to get the number of spaces in the given string.

str1 = "Hello World "
print(str1.count(' '))

Do comment if you have any questions and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Examples are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.