Python:空字符串计算为'false'

the*_*Dog 1 python base

我可能在一个独特的情况下,将空字符串评估为true将节省几行代码.(我理解空字符串计算为false.如下)

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

> non-empty string is true
Run Code Online (Sandbox Code Playgroud)

原因如下:

这没问题.但看看输出.

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

> baseN(32,16)
> 020
Run Code Online (Sandbox Code Playgroud)

更改最后一个结果(在递归结束时)打印出空字符串,给我错误.

 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
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为(num==0) and "" (false)总是会评估为False - >导致无终止的递归调用.

有没有办法只使用逻辑运算/表达式(没有if/else语句)来修复它?

以下将有效.但它不会只使用逻辑运算符.

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

baseN(32,16)
Run Code Online (Sandbox Code Playgroud)

bru*_*ers 6

Python有一个三元运算符:

def baseN(num,b):
    return baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b] if num else "" 
Run Code Online (Sandbox Code Playgroud)