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?
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.
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.
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!
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With