gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
python判断空
- User
python判断空
- Assistant
在Python中,你可以用各种方法来判断一个变量是否为空。"空"可以是None、空字符串、空列表、空字典、空集合等。下面是一些常用的判断方式:
使用 if not 语句
最简单的判断方式是使用
if not语句。在Python中,空的数据结构和None都被视为False。pythona = None if not a: print('a is empty or None') b = "" if not b: print('b is an empty string') c = [] if not c: print('c is an empty list') d = {} if not d: print('d is an empty dictionary') e = set() if not e: print('e is an empty set')使用 == 来具体判断
对于字符串、列表、字典和集合等类型,你也可以直接使用
==来判断它们是否为空。pythona = "" if a == "": print('a is an empty string') b = [] if b == []: print('b is an empty list') c = {} if c == {}: print('c is an empty dictionary') d = set() if d == set(): print('d is an empty set')