test1 = "this is test line" # non-empty string
test2 = "" # empty string
def test_line(line):
return line and not "is" in line
test1_result = test_line(test1)
test2_result = test_line(test2)
print(test1_result) # True
print(test2_result) # empty line printed
I've seen several ppl using this kind of code for boolean output
return someString and not partString in someString # "not" is optional
Why test2
results in empty line? And by adding someString
as an argument what additdional function we get compared to just using partString in someStirng
?
In your second function call with an empty string, when you essentially do
return "" and not "is" in ""
the and
expression gets short-circuited due to the first condition evaluating as False
essentially (you don't need both conditions to fail for an and
to fail) and hence it gets returned as an empty string. The second boolean condition won't be evaluated.
>>> bool("")
False
>>> "" and 1 == 1/0
''
>>> False and 1 == 1/0
False
But when you do it with a non-empty string, both parts of the boolean expression would be evaluated and thus giving exception, as expected
>>> bool("b")
True
>>> "b" and 1 == 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> "b" and 1 == 1
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.