Check if a string is empty in Python
This post will discuss how to check if a string is empty in Python.
1. Using == operator
A simple solution is to use the == operator to compare the given string with an empty string.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "" if s == "": print("The string is empty") |
Alternatively, you may use the != operator to check for a non-empty string:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "" if s != "": print("The string is not empty") |
2. Using not operator
The Pythonic way to check for an empty string is with the not operator as follows:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = "" if not s: print("The string is empty") else: print("The string is not empty") |
To check for non-empty string, you may do:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = "" if s: print("The string is not empty") else: print("The string is empty") |
3. Using len() function
Finally, you may use the len() function to check for an empty string that returns the length of a string.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "" if len(s) > 0: print("The string is empty") |
To check for non-empty strings, you can do:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "" if len(s): print("The string is not empty") |
That’s all about determining whether a string is empty in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)