标签归档:comparison-operators

如何检查字符串是否为空?

问题:如何检查字符串是否为空?

Python是否有类似空字符串变量的内容,您可以在其中执行以下操作:

if myString == string.empty:

无论如何,检查空字符串值的最优雅方法是什么?我""每次都很难检查空字符串,因此很难进行编码。

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.


回答 0

空字符串是“ falsy”,这意味着它们在布尔上下文中被认为是错误的,因此您可以执行以下操作:

if not myString:

如果您知道变量是字符串,则这是首选方法。如果您的变量也可以是其他类型,则应使用myString == ""。有关在布尔上下文中为假的其他值,请参见“ 真值测试 ”文档。

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.


回答 1

PEP 8“编程建议”部分中

对于序列(字符串,列表,元组),请使用以下事实:空序列为假。

因此,您应该使用:

if not some_string:

要么:

if some_string:

只是为了澄清,序列评估FalseTrue在布尔上下文如果它们是空的或不是。他们不等于FalseTrue

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.


回答 2

最优雅的方法可能是简单地检查其真实性或虚假性,例如:

if not my_string:

但是,您可能要删除空格,因为:

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

但是,您可能应该对此更加明确,除非您确定该字符串已经通过某种验证并且可以通过这种方式进行测试。

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.


回答 3

我会在剥离之前测试无。另外,我会使用一个空字符串为False(或Falsy)的事实。这种方法类似于Apache的StringUtils.isBlank番石榴的Strings.isNullOrEmpty

这就是我用来测试字符串是否为None或Empty或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

并且,与测试字符串是否不是None或NOR空或NOR空白完全相反:

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

上面代码的更简洁形式:

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

def isNotBlank (myString):
    return bool(myString and myString.strip())

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())

回答 4

我曾经写过类似Bartek的答案和javascript启发的东西:

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

测试:

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

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

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

Test:

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

回答 5

唯一真正可靠的方法是:

if "".__eq__(myString):

所有其他解决方案都可能存在问题,并且可能导致检查失败。

len(myString)==0如果myString是继承自str并覆盖的类的对象,则会失败__len__()方法方法方法。

同样myString == ""myString.__eq__("")如果myString覆盖__eq__()__ne__()

由于某种原因,"" == myString如果myString覆盖也将被愚弄__eq__()

myString is """" is myString等价。如果它们myString实际上不是字符串而是字符串的子类,则它们都将失败(都将返回False)。另外,由于它们是身份检查,所以它们起作用的唯一原因是因为Python使用了String Pooling(也称为String Internment),该字符串池在被插入的情况下使用相同的字符串实例(请参见此处:为什么使用’=来比较字符串=’或’是否’有时会产生不同的结果?)。和""从一开始就在CPython中进行实习

身份检查的最大问题是,据我所知,String Internment不规范要插入哪些字符串。从理论上讲""没有必要进行实习,而依赖于实现。

真正不能被愚弄的唯一方法是开头提到的方法:"".__eq__(myString)。由于此__eq__()方法明确调用了空字符串的方法,因此不能通过覆盖myString中的任何方法来欺骗它,并且可以与的子类牢固地结合使用str

如果对象覆盖了它的__bool__()方法,那么依靠字符串的虚假性也可能无法工作。

这不仅是理论上的工作,而且实际上可能与实际用法有关,因为我之前看到过框架和库的子类化str,并且使用myString is ""那里可能会返回错误的输出。

而且,is通常使用字符串比较字符串是一个很糟糕的陷阱,因为它有时会正确运行,而在其他时候则无法正常工作,因为字符串池遵循非常奇怪的规则。

也就是说,在大多数情况下,所有提到的解决方案都可以正常工作。这是大多数学术工作。

The only really solid way of doing this is the following:

if "".__eq__(myString):

All other solutions have possible problems and edge cases where the check can fail.

len(myString)==0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

Similarly myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__().

For some reason "" == myString also gets fooled if myString overrides __eq__().

myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result?). And "" is interned from the start in CPython

The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.

The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString). Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str.

Also relying on the falsyness of a string might not work if the object overrides it’s __bool__() method.

This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.

Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.


回答 6

测试空字符串或空字符串(较短的方法):

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

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

如果要区分空字符串和空字符串,建议使用if len(string),否则,建议仅使用if string其他人所说的方法。关于充满空格的字符串的警告仍然适用,因此请不要忘记strip

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.


回答 8

if stringname:false字符串为空时给出a 。我想这不可能比这更简单。

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


回答 9

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

回答 10

每次检查空字符串时,我都发现用硬编码“”不好。

干净的代码方法

这样做:foo == ""是非常不好的做法。""是一个神奇的价值。您永远都不应检查魔术值(通常称为魔术数)

您应该做的是与描述性变量名称进行比较。

描述性变量名称

可能会认为“ empty_string”是一种描述性变量名。不是

在去做之前,请empty_string = ""以为您有一个很好的变量名可以比较。这不是“描述性变量名称”的含义。

一个好的描述性变量名称基于其上下文。你要想想空字符串什么

  • 它从何而来。
  • 为什么在那儿。
  • 为什么您需要检查它。

简单表单字段示例

您正在构建一个表单,用户可以在其中输入值。您要检查用户是否写了什么。

一个好的变量名可能是 not_filled_in

这使得代码非常可读

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

全面的CSV解析示例

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

(由于CSV完全基于文本,因此无法表示 None使用预定义的关键字)

一个好的变量名可能是 CSV_NONE

如果您有一个新的CSV文件,该文件None用另一个字符串表示,则使代码易于更改和调整。""

if csvfield == CSV_NONE:
    csvfield = None

毫无疑问,这段代码是否正确。很明显,它做了应该做的事情。

比较一下

if csvfield == EMPTY_STRING:
    csvfield = None

这里的第一个问题是,为什么空字符串应该得到特殊对待?

这将告诉以后的编码人员,应该始终将空字符串视为None

这是因为它将业务逻辑(应为CSV值None)与代码实现(我们实际比较的是什么)混合在一起

两者之间需要分开关注

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)

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.

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.

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

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

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

A good variable name may be 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 ""

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)

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


回答 11

这个怎么样?也许它不是“最优雅的”,但是看起来很完整和清晰:

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

How about this? Perhaps it’s not “the most elegant”, but it seems pretty complete and clear:

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

回答 12

响应@ 1290。抱歉,无法格式化注释中的块。该None值在Python中不是空字符串,也不是(空格)。安德鲁·克拉克(Andrew Clark)的答案是正确的:if not myString。@rouble的答案是特定于应用程序的,不能回答OP的问题。如果您对“空白”字符串采用特殊定义,则会遇到麻烦。特别是,标准行为是str(None)产生'None'一个非空字符串。

但是,如果必须将Noneand(空格)视为“空白”字符串,这是一种更好的方法:

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())

例子:

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

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

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.

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

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.


回答 13

我觉得这很优雅,因为它可以确保它是一个字符串并检查其长度:

def empty(mystring):
    assert isinstance(mystring, str)
    if len(mystring) == 0:
        return True
    else:
        return False

I find this elegant as it makes sure it is a string and checks its length:

def empty(mystring):
    assert isinstance(mystring, str)
    if len(mystring) == 0:
        return True
    else:
        return False

回答 14

另一个简单的方法可能是定义一个简单的函数:

def isStringEmpty(inputString):
    if len(inputString) == 0:
        return True
    else:
        return False

Another easy way could be to define a simple function:

def isStringEmpty(inputString):
    if len(inputString) == 0:
        return True
    else:
        return False

回答 15

not str(myString)

对于空字符串,此表达式为True。非空字符串,None和非字符串对象都将产生False,但需要注意的是,对象可能会覆盖__str__以通过返回虚假值来阻止此逻辑。

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.


回答 16

您可能会看一下在Python中分配空值或字符串

这是关于比较空字符串。因此not,您可以测试您的字符串是否等于带有""空字符串的空字符串,而不是使用来测试是否为空。

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…


回答 17

对于那些期望像Apache StringUtils.isBlank或Guava Strings.isNullOrEmpty这样的行为的用户:

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

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

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

回答 18

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

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

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

    # your code for non-empty lines

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

回答 19

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

回答 20

如果你只是用

not var1 

不可能将一个布尔变量False与一个空字符串区别开''

var1 = ''
not var1
> True

var1 = False
not var1
> True

但是,如果您在脚本中添加简单条件,则会有所不同:

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

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

If you just use

not var1 

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

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

回答 21

如果这对某人有用,这是我构建的一种快速功能,可以用列表列表中的N / A替换空白字符串(python 2)。

y = [["1","2",""],["1","4",""]]

def replace_blank_strings_in_lists_of_lists(list_of_lists):
    new_list = []
    for one_list in list_of_lists:
        new_one_list = []
        for element in one_list:
            if element:
                new_one_list.append(element)
            else:
                new_one_list.append("N/A")
        new_list.append(new_one_list)
    return new_list


x= replace_blank_strings_in_lists_of_lists(y)
print x

这对于将列表列表发布到不接受某些字段空白的mysql数据库(在模式中标记为NN的字段,在我的情况下,这是由于复合主键引起的)非常有用。

In case this is useful to someone, here is a quick function i built out to replace blank strings with N/A’s in lists of lists (python 2).

y = [["1","2",""],["1","4",""]]

def replace_blank_strings_in_lists_of_lists(list_of_lists):
    new_list = []
    for one_list in list_of_lists:
        new_one_list = []
        for element in one_list:
            if element:
                new_one_list.append(element)
            else:
                new_one_list.append("N/A")
        new_list.append(new_one_list)
    return new_list


x= replace_blank_strings_in_lists_of_lists(y)
print x

This is useful for posting lists of lists to a mysql database that does not accept blanks for certain fields (fields marked as NN in schema. in my case, this was due to a composite primary key).


回答 22

我对”,’,’\ n’等字符串进行了一些实验。当且仅当变量foo是具有至少一个非空白字符的字符串时,我希望isNotWhitespace为True。我正在使用Python 3.6。我最终得到的是:

isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()

如果需要,可以将其包装在方法定义中。

I did some experimentation with strings like ”, ‘ ‘, ‘\n’, etc. I want isNotWhitespace to be True if and only if the variable foo is a string with at least one non-whitespace character. I’m using Python 3.6. Here’s what I ended up with:

isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()

Wrap this in a method definition if desired.


回答 23

如prmatta上面所述,但有误。

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

As prmatta posted above, but with mistake.

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