![]() The most efficient way is to use a combination of not and 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 strip() method In the below example, the strip() method returns true if it encounters whitespaces, thus solving the issue. In the above method, the strings with whitespaces are considered non-empty strings, and we can overcome this issue by using the strip() method, which truncates the whitespaces at both leading and trailing ends. If the values compared are not equal, then a value of false is. If the values compared are equal, then a value of true is returned. ![]() It returns either true or false depending on the result of the operation. String is not empty Using not+str.strip() method The not equal operator is a relational or comparison operator that compares two or more values (operands). The not operator can also perform similar to len() method and check if the length of the string is 0 or not internally.Īgain, the not operator considers the whitespaces a non-empty string similar to the len() method, which is invalid.Įxample – Check if the string is empty or not using not operator # Check if the string is empty or not using not operator # Check if the string is empty or not using len() method In the below example, we determine if the string is empty or not by checking if the length of the string is equal to 0 using the “if” statement. The string with empty spaces is actually an empty string, but the len() method treats whitespaces as Unicode characters and returns the length of the string. Check if the strA is empty : The string is. strA ''print ('Check if the strA is empty : ', end'') print ('The string is empty') print ('No it is not empty') Output. ![]() The not operator in Python checks the string with just spaces to be non-empty, which should not practically be True. Otherwise, it’s not empty.Įxample – Check if the string is empty or not using the len() method. Method 1: Checking empty string using not operator. If the len() method returns 0, it means the string is empty. We can use this technique to determine if the string is empty or not. The len() method is a built-in function in Python that returns the length of a string.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |