在Python中检查一个字符串是否为空的方法

212 阅读4分钟

在Python中,字符串数据类型是不可改变的,这意味着一旦定义,它就不能被改变。一个带有空格的字符串是一个具有非零长度的空字符串。

因此,当你使用 len() 或 not 操作符来检查空字符串时,它把空格算作字符串中的一个字符,所以带有空格的字符串不会被算作一个空字符串。在这篇文章中,我们将看看如何使用几种方法来检查一个字符串是否为空。

什么是 Python 中的 "字符串"?

一个字符序列被称为一个字符串。字符串可以由单引号或双引号中的字符组成。在 Python 中,三倍引号可以用来表示多行字符串和文档字符串。

my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

my_string = """Hello, welcome to
           the world Everyone"""
print(my_string)

输出:

Hello
Hello
Hello
Hello, welcome to
           the world of Everyone

Python字符串是一个内置的类型序列。在 Python 中,字符串可以用来管理文本数据。Python 字符串是不可改变的 Unicode 点序列。在Python中,最简单和最直接的方法是创建字符串。

检查字符串是否为空的方法

现在我们要看一下检查字符串是否为空的一些方法。

1.通过使用Not操作符

在Python中,not操作符验证一个只包含空格的字符串是不是空的,这不应该是这样的。

str1 = ""
# checking if the string is empty
print("Check if the str1 is empty : ", end="")
if(not str1):
    print("The string is empty")
else:
    print("No it is not empty")

输出:

Check if the str1 is empty : The string is empty

注意:如果我们在字符串中加入一个空格,它就不会被认为是空的,而not运算符将返回False。

2.通过使用 len() 函数

在Python中,使用len()函数来检查空字符串;如果它返回0,说明字符串是空的;否则就不是。

如果字符串包含一些东西,它将被认为是非空的;否则,它将被认为是空的。

str1 = ""

# checking if the string with space is empty
print("Check if the string is empty : ", end="")
if(len(str1)):
    print("The string is not empty")
else:
    print("The string is empty")

输出:

Check if the string is empty : The string is empty

在上面的例子中,如果条件变成了False,因为它返回0,这意味着else条件变成了True,字符串为空。

**注意:**在这个方法中,如果字符串包含空格,则不算是空字符串。

3.使用 len() + string.strip()

在Python中,使用len()+string.strip()方法来验证一个完全为空的字符串。strip()方法从一个字符串中删除空白。如果字符串中有任何空格,strip()方法将其删除,而len()函数将检查该字符串是否为空。

比如说

str1 = "   "

# checking if the string with space is empty
print("Check if the string is empty : ", end="")
if(len(str.strip())):
    print("The string is not empty")
else:
    print("The string is empty")

输出:

Check if the string is empty : The string is empty

无论你在字符串中放了多少个空格,它都会把它们全部剥离出来,并验证字符串的长度;如果它返回0,说明字符串是空的;否则就不是。

str1 = " ASK PYTHON  "

# checking if the string with space is empty
print("Check if the string is empty : ", end="")
if(len(str.strip())):
    print("The string is not empty")
else:
    print("The string is empty")

输出:

Check if the string is empty : The string is not empty

4.使用not + string.isspace()

string.isspace()函数确定字符串是否包含任何空格。如果字符串中有任何空格,它返回True。否则,返回False。这个方法比 strip() 方法更有效。

让我们看一下下面的例子。

str1 = "  "

# checking if the string with space is empty
print("Check if the string is empty : ", end="")
if(str and not str.isspace()):
    print("The string is not empty")
else:
    print("The string is empty")

输出:

Check if the string is empty : The string is empty

在上面的例子中,我们使用and运算符来检查isspace()函数的负条件。

如果其中一个条件变为假,"和运算符 "会使if条件返回假,而else条件则运行。

在Python中,这是对纯空字符串进行验证的最好方法。

总结

综上所述,我们学习了如何在Python中借助多种不同的方法来验证一个字符串是否为空。