gpt4 book ai didi

python - ""的含义?成员资格测试空字符串文字

转载 作者:太空狗 更新时间:2023-10-29 19:35:26 24 4
gpt4 key购买 nike

我偶然发现了 this显然是一段可怕的代码:

def determine_db_name():
if wallet_name in "":
return "wallet.dat"
else:
return wallet_name

if xx in "": 是什么意思?它不是总是评估为 False 吗?

最佳答案

如果 wallet_name 本身为空,它将返回 True:

>>> foo = ''
>>> foo in ''
True

虽然可怕。只需使用 if not wallet_name: 代替,或者使用 or 并完全取消 if 语句:

def determine_db_name():
return wallet_name or "wallet.dat"

因为 or 短路,返回 wallet_name 如果它不是空字符串,否则返回 "wallet.dat" .

关于python - ""的含义?成员资格测试空字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15813041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com