Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22466

Python for Beginners: Check if a String is Empty or Whitespace in Python

$
0
0

Strings in Python are used for handling text data. While doing operations on text data, we may need to remove empty strings or whitespaces. When we print an empty string or whitespaces, we cannot differentiate between the two. In this article, we will discuss different ways to check if a string is empty or whitespace in Python. This will help you to differentiate between an empty string and whitespace.

Check if a String is Empty or Whitespace in Python Using the Equality Operator

To check if a string is empty using the equality operator, we can just compare the string with another empty string. If the result is True, the input string is empty. Otherwise not.

input_string=""
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")

Output:

The input string is: 
Input string is an empty string.

To check whether the string contains only whitespace characters, you can compare it with an empty string. If the result is False, the string will be containing whitespace characters. You can observe this in the following example.

input_string=""
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is:  
Input string is a whitespace character.

Here, an input string that contains characters other than whitespaces will also return False as shown below.

input_string="Aditya"
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: Aditya
Input string is a whitespace character.

In the above example, you can see that we have used the string “Aditya”. However, the program tells us that the string contains only whitespaces. Hence, the program is logically incorrect. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using len() Function to Check if a String is Empty or Whitespace in Python

The len() function is used to find the length of an iterable object such as a list, string, tuple, etc. It takes the iterable object as its input argument and returns the length of the iterable object.

To check if a string is empty or whitespace using the len() function in Python, we will use the following steps.

  • First, we will find the length of the input string using the len() function. We will store the length in a variable str_len
  • Now, we will check if the length of the input string is 0.
  • If the length of the input string is 0, we will say that the string is an empty string. Otherwise, we will say that the string contains whitespaces. 

You can observe this in the following example.

input_string=""
print("The input string is:",input_string)
str_len=len(input_string)
if str_len==0:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: 
Input string is an empty string.

Again, if an input string contains characters other than whitespaces, the program will give wrong results as shown below.

input_string = "Aditya"
print("The input string is:", input_string)
str_len = len(input_string)
if str_len == 0:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: Aditya
Input string is a whitespace character.

Again, you can see that we have used the string“Aditya”. However, the program tells us that the string contains only whitespaces. Hence, the program is logically incorrect. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using the not Operator to Find if a String is Empty or Whitespace in Python

We can also use the not operator to check if a string is empty or whitespace in Python. 

In Python, all the iterable objects like strings, lists, and tuples evaluate to False when they are empty. Therefore, an empty string evaluates to False. 

To check if a string is empty or whitespace using the not operator, we will use the not operator on the input string. If the string is empty, the string will evaluate False. Then, the not operator will convert the result to True. 

Hence, if the output is True, we will say that the string is empty. Otherwise, we will say that the string contains whitespaces. You can observe this in the following example.

input_string = ""
print("The input string is:", input_string)
if not input_string:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: 
Input string is an empty string.

Again, if the input string contains characters other than whitespaces, the program will say that the string contains only whitespaces. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using For Loop to Check if a String is Empty or Whitespace in Python

There are six whitespace characters in python namely space “ ”, tab“\t”, newline “\n”, vertical tab ”\v”, carriage return “\r”, and “\f” feed. We can use a list of these whitespace characters and a for loop to check if a string is empty or whitespace in python. For this, we will use the following steps.

  • First, we will define a list named whitespaces to store the whitespace characters.
  • Then, we will define a variable isWhiteSpace and initialize it to True.
  • Now, we will check if the input string is an empty string using the equality operator. 
  • If the input string is an empty string, we will print so.
  • If the input string is not empty, we will iterate over the characters of the input string using a for loop.
  • Inside the for loop, we will check if the current character is a whitespace character using the membership operator and the whitespaces list.
  • If the current character is not a whitespace character, we will assign the value False to the variable isWhiteSpace. Then, we will break out of the for loop using the break statement.
  • Outside the for loop, if the isWhiteSpace is True, we will print that the string consists of only whitespace characters. 
  • Otherwise, we will print that the string contains characters other than whitespaces.

You can observe the entire process in the following example.

input_string = ""
whitespaces = ["", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
isWhiteSpace = True

if input_string == "":
    print("Input string is an empty string.")
else:
    for character in input_string:
        if character in whitespaces:
            continue
        else:
            isWhiteSpace = False
            break
if isWhiteSpace:
    print("The string contains only whitespace characters.")
else:
    print("The string contains characters other than whitespaces.")

Output:

The input string is: 
The string contains only whitespace characters.

Using List Comprehension to Find if a String is Empty or Whitespace in Python

List comprehension is used to create a list from an existing iterable object. However, we can use the all() function and list comprehension to check if an input string is empty or whitespace in Python. 

The all() function takes an iterable object as its input argument. It returns True if all the elements of the iterable object evaluate to True. Otherwise, it returns False.

To check if a string is empty or whitespace using list comprehension in Python, we will use the following steps.

  • First, we will define a list named whitespaces to store the whitespace characters.
  • Then, we will check if the input string is an empty string using the equality operator. 
  • If the input string is an empty string, we will print so.
  • If the input string is not empty, we will create a list of boolean values using list comprehension.
  • In list comprehension, we will include True in the output list if the character in the input string is a whitespace character. Otherwise, we will include False in the output list.
  • After creating the list of boolean values, we will pass it to the all() function. If the all() function returns True, it means that the string contains only whitespace characters. Therefore, we will print the same.
  • If the all() function returns False, we will print that the input string contains characters other than whitespace characters. 

You can observe the entire process in the following example.

input_string = ""
whitespaces = ["", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    myList = [True for character in input_string if character in whitespaces]
    output = all(myList)
    if output:
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is: 
The string contains only whitespace characters.

Check if a String is Empty or Whitespace in Python Using the strip() Method

The strip() method is used to remove leading or trailing spaces from a string. When invoked() on a string, removes the leading and trailing spaces from the string. After execution, it returns the modified string.

To check if a string is empty or whitespace in Python, we will use the following steps.

  • First, we will check if the string is empty using the equality operator. 
  • If the string is empty, we will print so. Otherwise, we will invoke the strip() method on the string.
  • If the strip() method returns an empty string, we can say that the original string contains only whitespace characters. Hence, we will print so.
  • If the strip() method returns a non-empty string, the input string contains characters other than whitespace characters. Therefore, we will print that the string contains characters other than whitespace characters. 

You can observe the entire process in the following example.

input_string = "   . "
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    newStr = input_string.strip()
    if newStr == "":
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is:    . 
The string contains characters other than whitespaces.

This approach works well even with the strings that contain characters other than whitespaces. Hence, you can use this approach in every situation.

Check if a String is Empty or Whitespace in Python Using the isspace() Method

The isspace() method is used to check if a string contains only whitespace characters. When invoked on a string, the isspace() method returns True if the string consists of only whitespace characters. Otherwise, it returns False.

To check if a string is empty or whitespace in Python using the isspace() method, we will use the following steps.

  • First, we will check if the string is empty or not using the equality operator.
  • If the string is empty, we will print so. Otherwise, we will invoke the isspace() method on the string.
  • If the isspace() method returns True, it means that the input string contains only whitespace characters. 
  • If the isspace() method returns False, the input string contains characters other than whitespace characters. Therefore, we will print that the string contains characters other than whitespace characters. 

You can observe this in the following example.

input_string = "  A "
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
elif input_string.isspace():
    print("The string contains only whitespace characters.")
else:
    print("The string contains characters other than whitespaces.")

Output:

The input string is:   A 
The string contains characters other than whitespaces.

Again, this approach works well even with the strings that contain characters other than whitespaces. Hence, you can use this approach in every situation.

Check if a String is Empty or Whitespace in Python Using Regular Expressions

Regular expressions are used to efficiently manipulate strings in python. We can also use regular expressions to check if a given string is empty or whitespace. For this, we will use the search() function.

The search() function takes a string pattern as its first input argument and a string as its second input argument. After execution, it returns a match object. If the substrings in the input string given as the second input argument to the search() function match the pattern given as the first input argument, the match object is not None. If the pattern does not exist in the string, the match object will be None.

To check if a given string is empty or whitespace character using the search() function, we will use the following steps.

  • First, we will check if the string is empty or not using the equality operator.
  • If the string is empty, we will print so. Otherwise, we will use the search() function to check if the string contains only whitespace characters.
  • As we need to check if the string contains only whitespaces, we will check if there are any non-white space characters in the string. For this, we will pass the pattern“\S” as the first input argument to the search() function. Also, we will pass the input string as the second input argument to the search() function.
  • If the search() function returns None, it means that there are no non-white space characters in the string. Hence, we will print that the string contains only whitespace characters.
  • If the search() function returns a match object, we will say that the string contains characters other than whitespace characters.

You can observe this in the following example.

from re import search

input_string = ""
pattern = "\\S"
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    match_object = search(pattern, input_string)
    if match_object is None:
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is:    
The string contains only whitespace characters.

Conclusion

In this article, we have discussed different ways to check if a string is empty or whitespace in Python. Out of all three approaches, the approach using equality operator, not operator, and the len() function are logically incorrect. They can be used only when we are sure that the input string will either be empty strings or will consist of only whitespace characters.

The approaches using the strip() method, the isspace() method, and the re.search() function are robust. These approaches can be used in all cases. Therefore, I suggest you use these approaches to check if a given string is empty or whitespace in Python.

To learn more about programming, you can read this article on data modeling tools. You might also like this article on regression in machine learning. You can also have a look at this article on data analyst vs data scientist that compares the salaries, education, and job responsibilities of a data analyst and a data scientist.

The post Check if a String is Empty or Whitespace in Python appeared first on PythonForBeginners.com.


Viewing all articles
Browse latest Browse all 22466

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>