theMobDog theMobDog - 1 year ago 118
Python Question

Python: Empty string evaluated to 'false'

I maybe in a unique situation where evaluating empty string as true would save a couple lines of code. (I understand empty string evaluate to false. as the following)

'' and print ("empty string is true")
'0' and print ("non-empty string is true")

> non-empty string is true

Here is why:

This works ok. But check out the output.

def baseN(num,b):
return (num == 0) and "0" or
(baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])

> baseN(32,16)
> 020

Changing the last result (at the end of the recursion) to print out empty string, gives me error.

def baseN(num,b):
return (num == 0) and "" or
( baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])

> baseN(32,16)
> File "<stdin>", line 2, in baseN
> RuntimeError: maximum recursion depth exceeded in comparison

This clearly wouldn't work because
(num==0) and "" (false)
would always evaluate to False -> leading to unterminated recursive call.

Is there a way to fix it using only the logical operations/expressions (without if/else statements) ?

The following will work. But it won't be using only logical operators.

def baseN(num,b):
if (num==0):
return ""
return (baseN(num // b, b)
+ "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])


Answer Source

Python has a ternary operator:

def baseN(num,b):
    return baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b] if num else "" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download