最优雅的方式检查Python中的字符串是空的吗?

时间:2022-11-14 20:21:11

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

Python有像一个空的字符串变量,你可以做什么?:

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.

无论如何检查空字符串值最优雅的方法是什么?我发现硬编码”“每次检查一个空字符串不是那么好。

21 个解决方案

#1


1320  

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

空字符串是“falsy”,这意味着它们在布尔环境中被认为是错误的,所以你可以这样做:

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.

这是首选方法,如果你知道你的变量是一个字符串。如果你的变量也可能是其他类型那么你应该使用myString = =””。看到其他值的真值测试文档中错误的布尔上下文。

#2


278  

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

从PEP 8日在“编程建议”部分:

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

对于序列(字符串、列表、元组),使用空序列为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.

澄清一下,序列是评估在一个布尔上下文或真或假,如果他们是空的。它们不等于假或真。

#3


147  

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.

但是,在这一点上,您应该更明确一点,除非您知道这个字符串已经通过了某种验证,并且是可以通过这种方式测试的字符串。

#4


52  

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

我将测试前noneness剥离。同样,我将使用空字符串为False(或Falsy)的事实。这种方法类似于Apache的stringutil的。isBlank或番石榴的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())

#5


21  

I once wrote something similar to Bartek's answer and javascript inspired:

我曾经写过类似Bartek的回答和javascript的启发:

def isNotEmpty(s):
    return bool(s and s.strip())

Test:

测试:

print isNotEmpty("")    # False
print isNotEmpty("   ") # False
print isNotEmpty("ok")  # True
print isNotEmpty(None)  # False

#6


10  

Test empty or blank string (shorter way):

测试空或空字符串(短):

if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

#7


9  

If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip.

如果你想区分空和null字符串,我建议使用如果len(字符串),否则,我建议使用简单的字符串如果其他人说。警告关于字符串的空格仍然适用,所以别忘了带。

#8


7  

a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True

#9


6  

I find hardcoding(sic) "" every time for checking an empty string not as good.

我发现硬编码(原文如此)”“每次检查一个空字符串不是那么好。

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

这样做:foo = "" "是非常糟糕的做法。“是一种神奇的价值。”你不应该检查魔法值(通常称为魔法数字)

What you should do is compare to a descriptive variable name.

你应该做的是与一个描述性的变量名。

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

人们可能认为“empty_string”是一个描述性变量名。它不是。

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

在您使用empty_string =“”之前,请您认为您有一个很好的变量名来比较。这不是“描述性的变量名”意味着什么。

A good descriptive variable name is based on its context. You have to think about what the empty string is.

良好的描述性的变量名是根据其上下文。你必须思考什么是空字符串。

  • Where does it come from.
  • 它从何而来?
  • Why is it there.
  • 为什么在那里。
  • Why do you need to check for it.
  • 你为什么要检查一下?

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

您正在构建一个用户可以输入值的表单。您需要检查用户是否写了一些东西。

A good variable name may be not_filled_in

一个好的可以not_filled_in变量名

This makes the code very readable

这使得代码非常可读

if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

您正在解析CSV文件,并希望将空字符串解析为None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

(因为CSV完全是基于文本的,所以如果不使用预定义的关键字,它不能表示None)

A good variable name may be CSV_NONE

一个好的变量名可以是CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

这使得代码容易改变和适应,如果你有一个新的CSV文件代表不是与另一个字符串"

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

如果这段代码是正确的,就没有问题了。很明显,它做了它应该做的事。

Compare this to

比较这

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

第一个问题是,为什么空字符串应该得到特殊处理?

This would tell future coders that an empty string should always be considered as None.

这将告诉未来的程序员,空字符串应该始终被视为无。

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

这是因为它混合了业务逻辑(CSV值应该为None)和代码实现(我们实际比较的是什么)

There needs to be a separation of concern between the two.

这两者之间需要有一个分离的关注点。

#10


5  

if my_string is '':

I haven't noticed THAT particular combination in any of the answers. I searched for

我没有注意到任何一个答案都有这种特殊的组合。我寻找

is ''

in the answers prior to posting.

在张贴前的答案。

 if my_string is '': print ('My string is NULL') # **footnote

I think this is what the original poster was trying to get to... something that reads as close to English as possible and follows solid programming practices.

我想这就是最初的海报想要达到的……读起来尽可能接近英语,并遵循可靠的编程实践。

if my_string is '':
    print('My string is NULL')
else:
    print(f'My string is {my_string}')

Character for character I think this solution is a good one.

我认为这是一个很好的解决方案。

I noted None has entered into the discussion, so adding that and compacting further we get:

我注意到没有人参与讨论,所以我补充说,并进一步压缩我们得到:

if my_string is '': print('My string is NULL')
elif my_string is None : print('My string.... isn\'t')
else: print(f'My string is {my_string}')

FOOTNOTE: How "wrong" would it be for a PEP to add a new keyword Null? Null == '' Prior to that happening, one could sneak this into a standard import Null = '' so that one can have the most English-like string checks.. hmmmm....

脚注:对于PEP添加新的关键字Null有多“错”?在发生这种情况之前,我们可以把它偷偷地放入一个标准的import Null = ",这样就可以有最像英语的字符串检查了。嗯....

if my_string is not Null:
    print(f'my_string is not Null and is {my_string}')

#11


4  

if stringname: gives a false when the string is empty. I guess it can't be simpler than this.

如果字符串为空,则字符串为false。我想再简单不过了。

#12


2  

Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

应对@1290。对不起,没有办法在注释中格式化块。None值不是Python中的空字符串,也不是(空格)。安德鲁·克拉克的答案是正确的:如果不是myString的话。@rouble给出的答案是特定于应用程序的,没有回答OP的问题。如果您采用“空白”字符串的特殊定义,您将会遇到麻烦。特别是,标准的行为是str(None)生成一个非空字符串“None”。

However if you must treat None and (spaces) as "blank" strings, here is a better way:

但是,如果您必须将None和(空格)视为“空白”字符串,这里有更好的方法:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

Examples:

例子:

>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
... 
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.

满足@rouble要求,同时不破坏字符串预期的bool行为。

#13


1  

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

对于那些期望有apache StringUtils这样的行为的人来说。isBlank或番石榴字符串。isNullOrEmpty:

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

#14


1  

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.

这个表达式对于空字符串是成立的。非空字符串、非空字符串和非字符串对象都将产生False,但需要注意的是,对象可能会重写__str__以通过返回一个假值来破坏此逻辑。

#15


0  

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

您可能会看到在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...

这是关于比较空的字符串。所以,不要用not来测试空,你可以用“”来测试你的字符串是否等于空字符串。

#16


0  

How about this? Perhaps it's not "the most elegant", but it seems pretty complete, clear, and safe to me:

这个怎么样?也许它不是“最优雅的”,但对我来说,它似乎相当完整、清晰、安全:

if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...

Is there a possibility for an exception or a false positive with this?

是否存在例外或假阳性的可能性?

#17


0  

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:

当您逐行读取文件并想确定哪一行为空时,请确保使用.strip(),因为“空”行中有新的行字符:

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

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

    # your code for non-empty lines

#18


0  

str = ""
if not str:
   print "Empty String"
if(len(str)==0):
   print "Empty String"

#19


0  

If you just use

如果你只使用

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

不可能将布尔值为False的变量与空字符串区分开来:

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

但是,如果您将一个简单的条件添加到脚本中,则会产生以下不同:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

#20


-1  

As prmatta posted above, but with mistake.

就像prmatta在上面说的,但是错误的。

def isNoneOrEmptyOrBlankString (myString):
    if myString:
        if not myString.strip():
            return True
        else:
            return False
    return False

#21


-6  

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循环来停止阅读Excel电子表格:

while str(MyString) != 'None':

#1


1320  

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

空字符串是“falsy”,这意味着它们在布尔环境中被认为是错误的,所以你可以这样做:

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.

这是首选方法,如果你知道你的变量是一个字符串。如果你的变量也可能是其他类型那么你应该使用myString = =””。看到其他值的真值测试文档中错误的布尔上下文。

#2


278  

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

从PEP 8日在“编程建议”部分:

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

对于序列(字符串、列表、元组),使用空序列为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.

澄清一下,序列是评估在一个布尔上下文或真或假,如果他们是空的。它们不等于假或真。

#3


147  

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.

但是,在这一点上,您应该更明确一点,除非您知道这个字符串已经通过了某种验证,并且是可以通过这种方式测试的字符串。

#4


52  

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

我将测试前noneness剥离。同样,我将使用空字符串为False(或Falsy)的事实。这种方法类似于Apache的stringutil的。isBlank或番石榴的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())

#5


21  

I once wrote something similar to Bartek's answer and javascript inspired:

我曾经写过类似Bartek的回答和javascript的启发:

def isNotEmpty(s):
    return bool(s and s.strip())

Test:

测试:

print isNotEmpty("")    # False
print isNotEmpty("   ") # False
print isNotEmpty("ok")  # True
print isNotEmpty(None)  # False

#6


10  

Test empty or blank string (shorter way):

测试空或空字符串(短):

if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

#7


9  

If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip.

如果你想区分空和null字符串,我建议使用如果len(字符串),否则,我建议使用简单的字符串如果其他人说。警告关于字符串的空格仍然适用,所以别忘了带。

#8


7  

a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True

#9


6  

I find hardcoding(sic) "" every time for checking an empty string not as good.

我发现硬编码(原文如此)”“每次检查一个空字符串不是那么好。

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

这样做:foo = "" "是非常糟糕的做法。“是一种神奇的价值。”你不应该检查魔法值(通常称为魔法数字)

What you should do is compare to a descriptive variable name.

你应该做的是与一个描述性的变量名。

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

人们可能认为“empty_string”是一个描述性变量名。它不是。

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

在您使用empty_string =“”之前,请您认为您有一个很好的变量名来比较。这不是“描述性的变量名”意味着什么。

A good descriptive variable name is based on its context. You have to think about what the empty string is.

良好的描述性的变量名是根据其上下文。你必须思考什么是空字符串。

  • Where does it come from.
  • 它从何而来?
  • Why is it there.
  • 为什么在那里。
  • Why do you need to check for it.
  • 你为什么要检查一下?

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

您正在构建一个用户可以输入值的表单。您需要检查用户是否写了一些东西。

A good variable name may be not_filled_in

一个好的可以not_filled_in变量名

This makes the code very readable

这使得代码非常可读

if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

您正在解析CSV文件,并希望将空字符串解析为None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

(因为CSV完全是基于文本的,所以如果不使用预定义的关键字,它不能表示None)

A good variable name may be CSV_NONE

一个好的变量名可以是CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

这使得代码容易改变和适应,如果你有一个新的CSV文件代表不是与另一个字符串"

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

如果这段代码是正确的,就没有问题了。很明显,它做了它应该做的事。

Compare this to

比较这

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

第一个问题是,为什么空字符串应该得到特殊处理?

This would tell future coders that an empty string should always be considered as None.

这将告诉未来的程序员,空字符串应该始终被视为无。

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

这是因为它混合了业务逻辑(CSV值应该为None)和代码实现(我们实际比较的是什么)

There needs to be a separation of concern between the two.

这两者之间需要有一个分离的关注点。

#10


5  

if my_string is '':

I haven't noticed THAT particular combination in any of the answers. I searched for

我没有注意到任何一个答案都有这种特殊的组合。我寻找

is ''

in the answers prior to posting.

在张贴前的答案。

 if my_string is '': print ('My string is NULL') # **footnote

I think this is what the original poster was trying to get to... something that reads as close to English as possible and follows solid programming practices.

我想这就是最初的海报想要达到的……读起来尽可能接近英语,并遵循可靠的编程实践。

if my_string is '':
    print('My string is NULL')
else:
    print(f'My string is {my_string}')

Character for character I think this solution is a good one.

我认为这是一个很好的解决方案。

I noted None has entered into the discussion, so adding that and compacting further we get:

我注意到没有人参与讨论,所以我补充说,并进一步压缩我们得到:

if my_string is '': print('My string is NULL')
elif my_string is None : print('My string.... isn\'t')
else: print(f'My string is {my_string}')

FOOTNOTE: How "wrong" would it be for a PEP to add a new keyword Null? Null == '' Prior to that happening, one could sneak this into a standard import Null = '' so that one can have the most English-like string checks.. hmmmm....

脚注:对于PEP添加新的关键字Null有多“错”?在发生这种情况之前,我们可以把它偷偷地放入一个标准的import Null = ",这样就可以有最像英语的字符串检查了。嗯....

if my_string is not Null:
    print(f'my_string is not Null and is {my_string}')

#11


4  

if stringname: gives a false when the string is empty. I guess it can't be simpler than this.

如果字符串为空,则字符串为false。我想再简单不过了。

#12


2  

Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

应对@1290。对不起,没有办法在注释中格式化块。None值不是Python中的空字符串,也不是(空格)。安德鲁·克拉克的答案是正确的:如果不是myString的话。@rouble给出的答案是特定于应用程序的,没有回答OP的问题。如果您采用“空白”字符串的特殊定义,您将会遇到麻烦。特别是,标准的行为是str(None)生成一个非空字符串“None”。

However if you must treat None and (spaces) as "blank" strings, here is a better way:

但是,如果您必须将None和(空格)视为“空白”字符串,这里有更好的方法:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

Examples:

例子:

>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
... 
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.

满足@rouble要求,同时不破坏字符串预期的bool行为。

#13


1  

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

对于那些期望有apache StringUtils这样的行为的人来说。isBlank或番石榴字符串。isNullOrEmpty:

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

#14


1  

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.

这个表达式对于空字符串是成立的。非空字符串、非空字符串和非字符串对象都将产生False,但需要注意的是,对象可能会重写__str__以通过返回一个假值来破坏此逻辑。

#15


0  

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

您可能会看到在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...

这是关于比较空的字符串。所以,不要用not来测试空,你可以用“”来测试你的字符串是否等于空字符串。

#16


0  

How about this? Perhaps it's not "the most elegant", but it seems pretty complete, clear, and safe to me:

这个怎么样?也许它不是“最优雅的”,但对我来说,它似乎相当完整、清晰、安全:

if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...

Is there a possibility for an exception or a false positive with this?

是否存在例外或假阳性的可能性?

#17


0  

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:

当您逐行读取文件并想确定哪一行为空时,请确保使用.strip(),因为“空”行中有新的行字符:

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

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

    # your code for non-empty lines

#18


0  

str = ""
if not str:
   print "Empty String"
if(len(str)==0):
   print "Empty String"

#19


0  

If you just use

如果你只使用

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

不可能将布尔值为False的变量与空字符串区分开来:

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

但是,如果您将一个简单的条件添加到脚本中,则会产生以下不同:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

#20


-1  

As prmatta posted above, but with mistake.

就像prmatta在上面说的,但是错误的。

def isNoneOrEmptyOrBlankString (myString):
    if myString:
        if not myString.strip():
            return True
        else:
            return False
    return False

#21


-6  

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循环来停止阅读Excel电子表格:

while str(MyString) != 'None':