
Problem –
You want to check whether a string is empty or not in python.
Solution –
There are various ways to check if a string is empty or not in python. Let’s look at them one by one.
Using len() –
You can use python built in len() function to check if a string is empty or not.
In [1]: str1 = ""
In [2]: str2 = "python"
In [3]: if len(str1) == 0:
...: print("String is empty")
...: else:
...: print("String is not empty")
...:
String is empty
In [4]: if len(str2) == 0:
...: print("String is empty")
...: else:
...: print("String is not empty")
...:
String is not empty
Using not –
You can also use not operator in python to check whether a string is empty or not.
In [5]: if not str1:
...: print("String is empty")
...: else:
...: print("String is not empty")
...:
String is empty
In [6]: if not str2:
...: print("string is empty")
...: else:
...: print("string is not empty")
...:
string is not empty