Python string null or empty

Python: Check if string is empty or blank or contain spaces only

In this article we will discuss different ways to check if a given string is either empty or contains only spaces.

Check if a string is empty using len()

len() function in python accepts a sequence as an argument and returns the number of elements in that sequence. So, if we pass a string as an argument to the len() function, then it returns the total number of characters in that string.

So, we can use this len() function to check if a string is empty or not, by checking if number of characters in the string are zero or not i.e.

msg = "" # check if string is empty if len(msg) == 0: print('String is empty') else: print('String is not empty')

Frequently Asked:

But if our variable contains None or blank spaces then this solution will not work.

Check if a string is empty using not

An empty string in python is equivalent to False in python. So, to check if a string is empty or not we can just apply “not” operator with it i.e.

msg = "" # check if string is empty or not if not msg: print('String is empty') else: print('String is not empty')

Unlike previous solution, this solution will work even if variable contains None i.e.

msg = None # check if string is empty or not if not msg: print('String is empty or None') else: print('String is not empty')

Using this technique we can check if a given string is empty or None. But if string is blank i.e. contains only white spaces then both these solutions will also not work. Let’s discuss different techniques to check if string is empty or contain spaces only,

Check if a string is empty or contain blank spaces only

Using strip():

We can use the strip() function of string to get a copy of string without leading and trailing whites paces. So, let’s use this to check if string is empty or contains only white spaces i.e.

msg = " " # Check if string is empty or contain spaces only if msg and msg.strip(): print('String is neither empty nor blank') else: print('String is either None or Empty or contain spaces only')
String is either None or Empty or contain spaces only

It stripped all the white spaces from front and end of the string and converted the blank string to an empty string. Then it check it checked if string is empty or not.

Using isspace()

isspace() function of string class returns True if string contains only white spaces. So we can use this to check if string is empty or contain white spaces only i.e.

msg = " " # Check if string is empty or contain spaces only if msg and not msg.isspace(): print('String is neither empty nor blank') else: print('String is either None or Empty or Blank')
String is either None or Empty or contain spaces only

Using Regex to check if a string is empty or contain blank spaces only in python

We can create a regex pattern that checks if the given string is either empty or contains only white spaces i.e.

import re msg = " " # Check if string is empty or contain spaces only if not msg or re.search("^\s*$", msg): print('String is either empty or Blank or contain only spaces') else: print('String is neither empty nor blank')
String is either None or Empty or contain spaces only

Here we checked if the given string started with zero or more white spaces and contains only whitespaces after that, till the end.

Читайте также:  Loc python что делает

Another example to check if string is empty or contain only spaces, using regex,

import re msg = "" # Check if string is empty or contain spaces only if not msg or re.search("^\s*$", msg): print('String is either empty or Blank or contain only spaces') else: print('String is neither empty nor blank')
String is either None or Empty or contain spaces only

So, here we discussed four different techniques to check if a given string is empty or blank in python.

The complete example is as follows,

import re def main(): print('*** Check if a string is empty using len() in Python *** ') msg = "" # check if string is empty if len(msg) == 0: print('String is empty') else: print('String is not empty') print('*** Check if a string is empty using "not" operator in python *** ') msg = "" # check if string is empty or not if not msg: print('String is empty') else: print('String is not empty') msg = None # check if string is empty or not if not msg: print('String is empty or None') else: print('String is not empty') print('Check if a string is empty by comparing with "" ') msg = "" if msg == "": print('String is empty') else: print('String is not empty') print('*** Check if a string is empty or contain blank spaces only ***') print('***** Check if a string is empty or contain blank spaces only using strip() ****') msg = " " # Check if string is empty or contain spaces only if msg and msg.strip(): print('String is neither empty nor blank') else: print('String is either None or Empty or contain spaces only') print('***** Check if a string is empty or contain blank spaces only using isspace() ****') msg = " " # Check if string is empty or contain spaces only if msg and not msg.isspace(): print('String is neither empty nor blank') else: print('String is either None or Empty or Blank') print('***** Using Regex to check if a string is empty or contain blank spaces only in python ****') print('Example 2:') msg = " " # Check if string is empty or contain spaces only if not msg or re.search("^\s*$", msg): print('String is either empty or Blank or contain only spaces') else: print('String is neither empty nor blank') print('Example 2:') msg = "" # Check if string is empty or contain spaces only if not msg or re.search("^\s*$", msg): print('String is either empty or Blank or contain only spaces') else: print('String is neither empty nor blank') if __name__ == '__main__': main()
*** Check if a string is empty using len() in Python *** String is empty *** Check if a string is empty using "not" operator in python *** String is empty String is empty or None Check if a string is empty by comparing with "" String is empty *** Check if a string is empty or contain blank spaces only *** ***** Check if a string is empty or contain blank spaces only using strip() **** String is either None or Empty or contain spaces only ***** Check if a string is empty or contain blank spaces only using isspace() **** String is either None or Empty or Blank ***** Using Regex to check if a string is empty or contain blank spaces only in python **** Example 2: String is either empty or Blank or contain only spaces Example 2: String is either empty or Blank or contain only spaces

Источник

Читайте также:  Java соединение с сервером

How to Check if a String is Empty or None in Python

In Python, it’s often important to check whether a string is empty or None before performing operations on it. This can prevent unexpected errors and make your code more robust. But what is the most efficient and Pythonic way to do this? And what potential pitfalls should you watch out for?

In this article, we’ll explore these questions, demonstrating how to correctly check if a string is empty or None in Python, as well as discussing some best practices to make your code more reliable and maintainable.

Boolean Evaluation in Python

In Python, values are considered «truthy» or «falsy» based on whether they evaluate to True or False in a boolean context. This concept plays a crucial role when checking conditions in code.

For strings, an empty string ( «» ) is considered «falsy» — it evaluates to False in a boolean context. On the other hand, a non-empty string is «truthy» — it evaluates to True . The special value None is also considered «falsy», as shown in the following code snippet:

s1 = "" s2 = "Hello" s3 = None print(bool(s1)) # False print(bool(s2)) # True print(bool(s3)) # False 

This property of strings and None is extremely useful when you want to check if a string is empty or None . As we’ll see in the next sections, you can use simple if statements to make these checks, leveraging the «falsiness» of an empty string and None .

Checking if a String is Empty

When checking if a string is empty in Python, we can take advantage of the fact that an empty string is «falsy». You can use either the == operator or the not operator to perform this check.

Method 1: Using the == Operator

s = "" if s == "": print("String is empty") else: print("String is not empty") 

Method 2: Using the not Operator

s = "" if not s: print("String is empty") else: print("String is not empty") 

In both of these methods, the if statement will print «String is empty» if the string s is empty. The not operator in the second example negates the «truthiness» or «falsiness» of the string, making the code slightly more concise. This is a common Pythonic way to check for empty strings.

Checking if a String is None

In Python, to check if a string is None , it’s best practice to use the is operator rather than the == operator. This is because is checks if both operands are the same object, not just equivalent.

Advice: Read more about the differences between the is and the == operators in our article «‘is’ vs ‘==’ in Python — Object Comparison».

Читайте также:  При прокрутке страницы html

Let’s take a look at the practical use-case of the is operator for checking if a string is None «:

s = None if s is None: print("String is None") else: print("String is not None") 

As expected, the if statement will print «String is None» if the variable s is None .

Remember, None is a singleton in Python, which means there is only ever one instance of None . Thus, using is is more appropriate and can be more efficient when checking for None .

Checking if a String is Empty or None

To check if a string is either empty or None in Python, we’ll combine the techniques we discussed in the previous sections. We’ll use an or operator to check both conditions at once:

s = "" # Try also with s = None if s is None or s == "": print("String is empty or None") else: print("String is not empty and not None") 

Advice: Find out more about the or operator in Python by reading our «Guide to the Python or Operator».

In this example, the if statement checks two conditions: if s is None and if s is an empty string. If either condition is true, it will print «String is empty or None» . If both conditions are false (meaning the string is not None and it’s not empty), it will print «String is not empty and not None» .

Tips and Advice

Don’t use == Instead of is to Check for None

Python has two equality operators, == and is . While they sometimes work the same, they are not identical. The == operator checks for value equality, while is checks for identity, meaning that it checks whether the operands are the same object.

None is a singleton in Python — there’s only one instance of None . Therefore, it’s more appropriate and slightly more efficient to use is when checking for None .

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

s = None # Recommended if s is None: print("s is None") # Not recommended if s == None: print("s is None") 

Take Advantage of Python’s «Truthiness»

Python’s treatment of different values as «truthy» or «falsy» in boolean contexts can simplify your code. Rather than explicitly comparing a string to an empty string ( «» ), you can use the not keyword to check if a string is empty:

s = "" # Recommended if not s: print("String is empty") # Not recommended if s == "": print("String is empty") 

Handle None When Performing Operations on Strings

If there’s any chance a string could be None , always check before performing operations on it. Neglecting to do so can result in a TypeError :

s = None # Results in TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' print(s + " more text") 

To prevent such errors, you can check if the string is None before performing the operation:

if s is not None: print(s + " more text") else: print("String is None, cannot perform operation") 

Conclusion

We’ve seen that Python provides straightforward and efficient ways to perform these checks, leveraging the «truthiness» and «falsiness» of different values in boolean contexts. We’ve also discussed some potential pitfalls to avoid and best practices to follow when performing these checks, such as using the is operator to check for None and the not operator to check for an empty string.

Источник

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