17
loading...
This website collects cookies to deliver better user experience
len()
method is a built-in function in Python that returns the length of a string. We can use this technique to determine if the string is empty or not. len()
method returns 0, it means the string is empty. Otherwise, it’s not empty.len()
method treats whitespaces as Unicode characters and returns the length of the string.# Check if the string is empty or not using len() method
text1 = ""
text2 = " "
text3 = "Hello World"
print("Length of text1 :", len(text1))
print("Length of text2 :", len(text2))
print("Length of text3 :", len(text3))
if(len(text1) == 0):
print("String is empty")
else:
print("String is not empty")
if(len(text2) == 0):
print("String is empty")
else:
print("String is not empty")
if(len(text3) == 0):
print("String is empty")
else:
print("String is not empty")
Length of text1 : 0
Length of text2 : 5
Length of text3 : 11
String is empty
String is not empty
String is not empty
len()
method and check if the length of the string is 0 or not internally. len()
method, which is invalid.# Check if the string is empty or not using not operator
text1 = ""
text2 = " "
text3 = "Hello World"
if(not text1):
print("String is empty")
else:
print("String is not empty")
if(not text2):
print("String is empty")
else:
print("String is not empty")
if(not text3):
print("String is empty")
else:
print("String is not empty")
String is empty
String is not empty
String is not empty
strip()
method, which truncates the whitespaces at both leading and trailing ends.strip()
method returns true if it encounters whitespaces, thus solving the issue.# Check if the string is empty or not using not operator and strip() method
text1 = ""
text2 = " "
text3 = "Hello World"
if(not (text1 and text1.strip())):
print("String is empty")
else:
print("String is not empty")
if(not (text2 and text2.strip())):
print("String is empty")
else:
print("String is not empty")
if(not (text3 and text3.strip())):
print("String is empty")
else:
print("String is not empty")
String is empty
String is empty
String is not empty
str.isspace()
method because the strip()
method has to remove the whitespaces, and it’s a costly operation when compared to the issapce()
method.# Check if the string is empty or not using not operator and isspace() method
text1 = ""
text2 = " "
text3 = "Hello World"
if(not (text1 and not text1.isspace())):
print("String is empty")
else:
print("String is not empty")
if(not (text2 and not text2.isspace())):
print("String is empty")
else:
print("String is not empty")
if(not (text3 and not text3.isspace())):
print("String is empty")
else:
print("String is not empty")
String is empty
String is empty
String is not empty