如何检查字符串是否为空? [英] How to check if the string is empty?

查看:67
本文介绍了如何检查字符串是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 是否有类似空字符串变量的东西,您可以在其中执行:

Does Python have something like an empty string variable where you can do:

if myString == string.empty:

无论如何,检查空字符串值的最优雅的方法是什么?我发现硬编码 "" 每次检查空字符串都不太好.

Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.

推荐答案

空字符串是假的"(python 2python 3 参考),这意味着它们在布尔上下文中被认为是假的,所以你可以这样做:

Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:

if not myString:

如果您知道您的变量是一个字符串,这是首选方式.如果您的变量也可以是其他类型,那么您应该使用 myString == "".请参阅有关 真值测试 的文档,了解其他错误值在布尔上下文中.

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use myString == "". See the documentation on Truth Value Testing for other values that are false in Boolean contexts.

这篇关于如何检查字符串是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆