Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if there's any empty string in multiple strings

I know it's a basic question but please bear with me. Let's say if we have 4 strings below:

a = ''
b = 'apple'
c = 'orange'
d = 'banana'

So, normally if I want to check if any of the three string a b c is empty, I could use len() function.

if len(a) == 0 or len(b) == 0 or len(c) == 0:
    return True

But then I thought it is too troublesome to write like above if I have many strings. So, I used

if not a:
    return True

But, when i am checking for multiple strings b c d using the above method, it returns True and I am puzzled as non of the strings b c d where empty.

if not b or c or d:
    return True

What is going on?

like image 439
Chris Aung Avatar asked May 07 '14 01:05

Chris Aung


People also ask

How do you check if multiple strings exist in another string in Python?

Use the any() function to check if multiple strings exist in another string, e.g. if any(substring in my_str for substring in list_of_strings): . The any() function will return True if at least one of the multiple strings exists in the string.

How do you check if the string is empty or blank in Python?

Check if a string is empty using len() So, if we pass a string as an argument to the len() function, then it returns the total number of characters in that string. So, we can use this len() function to check if a string is empty or not, by checking if number of characters in the string are zero or not i.e.

How do you check if a text field is empty in Python?

Use an if statement to check if a user input is empty, e.g. if country == '': . The input() function is guaranteed to return a string, so if it returns an empty string, the user didn't enter a value. Copied!

How do you check if a list of strings is empty?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String.Empty, or it consists only of white-space characters.


1 Answers

The problem lies with this line:

if not b or c or d:

You need to include the "not" condition for each string. So:

if not b or not c or not d:

You could also do it like this:

    return '' in [a, b, c, d]
like image 79
James Scholes Avatar answered Sep 28 '22 02:09

James Scholes