Skip to main content
 首页 » 编程设计

Python:评估为 'false' 的空字符串

2025年05月04日19lautakyan007

我可能处于一种独特的情况下,将空字符串评估为 true 会节省几行代码。 (我理解空字符串评估为 false。如下所示)

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

原因如下:

这工作正常。但是请检查输出。

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

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

 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 

这显然行不通,因为 (num==0) 和 ""(false) 的计算结果总是 False -> 导致未终止的递归调用。

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

以下将起作用。但它不会只使用逻辑运算符。

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

请您参考如下方法:

Python 有一个三元运算符:

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