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:04

You may have a look at this Assigning empty value or string in Python

This is about comparing strings that are empty. So instead of testing for emptiness with not, you may test is your string is equal to empty string with "" the empty string...

查看更多
深知你不懂我心
3楼-- · 2019-01-01 05:04
str = ""
if not str:
   print "Empty String"
if(len(str)==0):
   print "Empty String"
查看更多
听够珍惜
4楼-- · 2019-01-01 05:04

When you are reading file by lines and want to determine, which line is empty, make sure you will use .strip(), because there is new line character in "empty" line:

lines = open("my_file.log", "r").readlines()

for line in lines:
    if not line.strip():
        continue

    # your code for non-empty lines
查看更多
不再属于我。
5楼-- · 2019-01-01 05:08

I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty

This is what I would use to test if a string is either None OR Empty OR Blank:

def isBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return False
    #myString is None OR myString is empty or blank
    return True

And, the exact opposite to test if a string is not None NOR Empty NOR Blank:

def isNotBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return True
    #myString is None OR myString is empty or blank
    return False

More concise forms of the above code:

def isBlank (myString):
    return not (myString and myString.strip())

def isNotBlank (myString):
    return bool(myString and myString.strip())
查看更多
登录 后发表回答