Most elegant way to check if the string is empty in 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.


Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just do this:

if not 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.


From PEP 8, in the “Programming Recommendations” section:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

So you should use:

if not some_string:

or:

if some_string:

Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True .


The most elegant way would probably be to simply check if its true or falsy, eg:

if not my_string:

However, you may want to strip white space because:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.

链接地址: http://www.djcxy.com/p/3302.html

上一篇: 如何使用Ajax发送FormData对象

下一篇: 最优雅的方法来检查在Python中的字符串是否为空?