Python 如何检查字符串是否为空?
空字符串判断用 if not s:;要同时把纯空白(空格/制表符)当空用 if not s.strip():。本文给出写法与 None、空白的区分处理。
判空:if not s:(空字符串布尔值为 False);把"全是空格"也算空:if not s.strip():。注意 not s 对 None 也为 True,需要区分时用 if s is None 单独判断。
基本写法
s = ""
if not s:
print("空字符串") # ✅ 推荐
if s == "":
print("也能用,但不 Pythonic")
纯空白也算空
s = " \t\n "
if not s.strip():
print("空或全是空白")
区分 None、空串、空白
def check(s):
if s is None:
return "None"
if not s.strip():
return "空或空白"
return "有内容"
常见问题(FAQ)
Q:strip() 会改原字符串吗? 不会——返回新字符串。
Q:表单输入校验推荐哪种? not s or not s.strip() 合并写:if not (s and s.strip()):。