Most elegant way to check if the string is empty i

2019-01-01 04:38发布

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.

22条回答
笑指拈花
2楼-- · 2019-01-01 05:00

In my experience testing for "" doesn't always work. This simple tests has always worked for me:

if MyString == 'None'

or

if MyString != 'None'

Reading an Excel spreadsheet I want to stop when a column gets empty using the following while loop:

while str(MyString) != 'None':
查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 05:01
a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True
查看更多
牵手、夕阳
4楼-- · 2019-01-01 05:02

As prmatta posted above, but with mistake.

def isNoneOrEmptyOrBlankString (myString):
    if myString:
        if not myString.strip():
            return True
        else:
            return False
    return False
查看更多
宁负流年不负卿
5楼-- · 2019-01-01 05:03

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.

查看更多
爱死公子算了
6楼-- · 2019-01-01 05:03

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

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.

查看更多
栀子花@的思念
7楼-- · 2019-01-01 05:04
not str(myString)

This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.

查看更多
登录 后发表回答