空值校验在数据处理中是一项基础而重要的任务。Python中有多种数据对象,每种都有其特定的空值表示方法和校验方式。本文将深入探讨这些内容,并提供丰富的示例代码帮助读者理解。
None类型
在Python中,None是表示空值的对象。你可以使用is None来检查变量是否为空。
x = None
if x is None:
print("x is None")
else:
print("x is not None")
空字符串
空字符串在Python中使用''或""表示。可以使用if not s来检查字符串是否为空。
s = ''
if not s:
print("s is empty")
else:
print("s is not empty")
空列表、元组和集合
空列表、元组和集合分别用[]、()和set()表示,可以使用if not container来检查是否为空。
empty_list = []
if not empty_list:
print("empty_list is empty")
else:
print("empty_list is not empty")
空字典
空字典使用{}表示,可以使用if not d来检查是否为空。
empty_dict = {}
if not empty_dict:
print("empty_dict is empty")
else:
print("empty_dict is not empty")
空文件对象
在处理文件时,可以使用os.path.getsize(filename)来检查文件是否为空。
import os
filename = 'empty_file.txt'