If you need to check if a String is empty or not in Python then you have the following options.
Using len() function to check if String is empty
You can check length of String in Python using len() function. If String is of length zero that means it is an empty string. Here note that String with only whitespaces is considered a non-zero length string, if you want to evaluate such string also as empty string then use strip() method to strip spaces before checking the length of the String.
def check_if_empty(string): print('length of String', len(string)) if len(string) == 0: print('empty String') str1 = "" check_if_empty(str1) str2 = " " check_if_empty(str2)
Output
length of String 0 empty String length of String 3
As you can see str2 which is a String with whitespaces is not a length zero String so not considered empty. You need to strip whitespaces for such strings.
def check_if_empty(string): print('length of String', len(string)) if len(string.strip()) == 0: print('empty String') str1 = "" check_if_empty(str1) str2 = " " check_if_empty(str2)
Output
length of String 0 empty String length of String 3 empty String
Using not to check if String is empty
An empty String is considered false in boolean context so using not string you can find whether the String is empty or not. Here note that String with only whitespaces is not considered false so you need to strip whitespaces before testing for such strings.
def check_if_empty(string): if not string.strip(): print('empty String') str1 = "" check_if_empty(str1) str2 = " " check_if_empty(str2)
Output
empty String empty String
Using not with str.isspace() method
An empty String is considered false in boolean context and str.isspace() method returns true if there are only whitespace characters in the string and there is at least one character. Using str.isspace() method to check for strings having only whitespaces and not keyword to check for empty strings you can create a condition to check for empty strings including those strings which have only whitespaces.
def check_if_empty(string): if not string or string.isspace(): print('empty String') str1 = "" check_if_empty(str1) str2 = " " check_if_empty(str2) str3 = "netjs" check_if_empty(str3)
Output
empty String empty String
As you can see both str1 and str2 are considered empty strings.
That's all for this topic Check String Empty or Not in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-