Test if string is empty python

How to check if string is empty in Python?

In some applications, it is compulsory to fill data into an input field. In such cases, they are marked with an asterisk * . Have you ever thought that how is this implemented in the backend? In this article, we will cover various different ways to check whether an input string is empty or not in Python.

Читайте также:  Назначение переменной в python

In a simple form on any website, when a user tries to fill in the next field of data without filling in the compulsory field or when the user tries to Submit/Save the page/form without filling in the compulsory field(s), it throws a warning which indicates that one/more of the compulsory fields haven’t been filled.

This is usually implemented by checking if the data entered by the user is empty or not.

In Python, this could be done in many ways. They are listed below:

1. Using the not operator with the if condition To Check if a String is Empty in Python

The Programming Recommendations (PEP 8) suggest that the not an operator could be used in conjunction with the if condition, when the data type of the variable being checked for emptiness is known beforehand.

This can be used for lists and tuples as well. A non-empty string evaluates to True when used with a if condition and an empty string evaluate to False. So we can use the if condition for checking whether a given string is empty or not. We can also use it with the not operator which negates the output, hence it makes it more logical if we have to check for an empty string that we use the not keyword with it. So if a string is empty, it returns False, and with not the operator, it will return True.

Let’s take an example and see,

my_string = '' if not my_string: print("The string is empty") else: print("The string is not empty") 

Here is another example showing how a non-empty string is evaluated.

my_string = 'Studytonight' if not my_string: print("The string is empty") else: print("The string is not empty")

So, you can use a simple if-else condition too, but it makes more sense code-wise to use the not operator if you have to check for an empty string. Using not the operator with the string will return True if the string is empty.

2. Using the strip method To Check if a String is Empty in Python

Sometimes, a string might contain blank spaces, which makes it non-empty. Hence while checking for an empty string we also need to check whether the string has only spaces. This can be done using the strip method.

Let’s take an example where we will be using the strip method to remove the empty spaces from the given string and will then check if it is empty or not.

def check_for_Blanks(myString): # myString is not None AND myString is not empty or blank if myString and myString.strip(): return False # myString is None OR myString is empty or blank return True print(check_for_Blanks(' ')) print(check_for_Blanks('')) print(check_for_Blanks(None)) print(check_for_Blanks(' Studytonight '))

The above code can also be written as follows(more PYTHONIC way), which would give the same output as the above code,

def check_for_Blanks (myString): return not (myString and myString.strip()) print(check_for_Blanks(' ')) print(check_for_Blanks('')) print(check_for_Blanks(None)) print(check_for_Blanks(' Studytonight '))

3. Using the __ eq__ method To Check if a String is Empty in Python

The dunder basically means methods that have double underscores before and after their names.

myString = 'StudyTonight' if "".__eq__(myString): print("Empty string") else: print("Non-empty string")

Let’s run the above code with an empty string,

myString = '' if "".__eq__(myString): print("Empty string") else: print("Non-empty string")

4. Using the len method To Check if a String is Empty in Python

The len method gives the length of the input string and it indicates if the string is non-empty when the length of the string is greater than 0.

myString = 'Studytonight' if len(myString) == 0: print("Empty String") else: print("Non-empty String")

5. Using the strip method only To Check if a String is Empty in Python

The strip method is usually used to remove blank spaces present in a string. Usually, if a string has only blank spaces it is considered empty but it may or may not be considered empty depending on the use case. In our case, we will consider a string with only empty spaces as empty.

myString = ' ' if myString.strip(): print("It is neither empty nor blank") else: print("It is either empty or blank")
It is either empty or blank

Let’s take another example:

myString = ' Studytonight ' if myString.strip(): print("It is neither empty nor blank") else: print("It is either empty or blank")
It is neither empty nor blank

Note: Strings being empty and strings being blank are two different things. An empty string is when the string doesn’t have any character, or whitespace whatsoever. On the other hand, a blank string means a string that has multiple white spaces or tab spaces. In the above example, both conditions are being checked for.

Conclusion

Checking for empty lines and whitespace is a frequent Python computing prerequisite. We saw in this article how to verify an empty string in Python using the len() function, comparing it to an empty string literal, and using the string’s boolean value. We also looked at how to use the string function isspace to check for spaces( ). If you believe we overlooked something or have an alternative approach, please share it in the comments area below. Incorporating these methods into your Python code can improve the robustness and efficiency of your applications.

Frequently Asked Questions(FAQs)

1. What is an empty string in Python?

An empty string in Python is a string with no characters or a length of zero. It is denoted by two quotes with nothing in between them: «».

2. How can I check if a string is empty in Python?

You can check if a string is empty in Python using the not operator, which returns True if the string is empty and False otherwise. Here’s an example code snippet:

my_string = "" if not my_string: print("The string is empty.") else: print("The string is not empty.")

3. What is the len() function in Python and how can it be used to check for an empty string?

The len() function in Python returns the length of a string, which is zero for an empty string. You can use the len() function to check if a string is empty by comparing its length to zero. Here’s an example code snippet:

my_string = "" if len(my_string) == 0: print("The string is empty.") else: print("The string is not empty.")

4. What is the strip() method in Python and how can it be used to check for an empty string?

The strip() method in Python removes leading and trailing whitespace from a string. You can use the strip() method to check if a string is empty by first stripping it and then checking if its length is zero. Here’s an example code snippet:

my_string = " " if len(my_string.strip()) == 0: print("The string is empty.") else: print("The string is not empty.") 

You may also like:

Источник

How to Check if a String is Empty in Python

How to Check if a String is Empty in Python Cover Image

In this tutorial, you’ll learn how to use Python to check if a string is empty or not. Being able to work with strings and see whether or not they are empty is an important skill to learn. Python strings are immutable, meaning that they cannot be changed once they’re created. Because of this, it can be useful to check if a string is empty or not.

By the end of this tutorial, you’ll have learned:

  • What is considered an empty string in Python
  • How to use the not keyword to check if a string is empty
  • How to check if a string is empty based on its length

How to Create an Empty String in Python

In Python, you can create an empty string in a number of ways. The simplest, and clearest, way is simply to create a string with nothing in it. This can be done using either single, double, or triple quotes. Let’s see what this looks like:

# Creating an Empty String in Python empty1 = '' empty2 = "" empty3 = """"""

Similarly, we can use the string constructor function str() to create an empty string in Python. Let’s see what this looks like and print it out:

# Creating an Empty String in Python empty = str() print(empty) # Returns #

Are Strings of Spaces Considered Empty in Python?

In the examples above, the strings were truly empty. Now, take a string like this for example:

Would we consider this empty? Well, it depends. From a technical perspective, the string isn’t empty. From a practical perspective, the string is empty. To get semantics out of the way, let’s consider a string that’s made up entirely of spaces or whitespace to be “blank”.

Use not To Check if a String is Empty in Python

The simplest, and most Pythonic, way of checking if a string is empty in Python is to simply use an if-else block with the not keyword. Empty strings in Python are considered to be falsy, meaning that they evaluate to False .

Because of this, we can easily check if a string is empty by checking its boolean truth:

# Checking if a String is Empty in Python string = '' print(not string) # Returns: True

What this expression evaluates to is not False , which then evaluates to True .

A cleaner, and more practical way to write this, is using an if-else block. With this we can run an expression when a string is empty or not:

# Checking if a String is Empty with an if-else string = '' if not string: print("Empty string!") else: print("Not empty string!") # Returns: # Empty string!

In the next section, you’ll learn how to check if a string is empty using the len() function.

Use len to Check if a String in Empty in Python

Because empty strings in Python are, well, empty, you can also check the length of a string to see if it’s empty or not. This is done using the len() function, which returns the length of an iterable object passed into it.

Let’s see how we can use this function to check if a string is empty or not:

# Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string!

Keep in mind that this only checks if a string is truly empty. In the following section, you’ll learn how to check if a string is either empty or blank.

Use strip to Check if a String is Blank in Python

In this section, you’ll learn how to check if a string is both empty as well as blank, meaning that it only contains whitespace. In order to do this, we first need to apply the .strip() method to the string, which returns a string without any whitespace. We can then use either not keyword or the len() function to check if it’s empty.

Let’s see what this looks like. We’ll create a string that contains a few spaces and combine the .strip() method with the not keyword:

# Checking if a String is Blank in Python string = ' ' if not string.strip(): print("Blank string!") else: print("Not blank string!") # Returns # Blank string!

Note that because strings in Python are immutable, the original string will not be modified.

Conclusion

In this tutorial, you learned how to use Python to check if a string is empty or blank. You first learned how to create an empty string in Python, using either direct assignment or the string constructor. Then, you learned how to check if a string was empty using the not keyword and the len() function. Following this, you learned how to work with blank strings, meaning strings that only contain whitespace.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

Оцените статью