Programa de Python para verificar si la string está vacía o no

Las strings de Python son inmutables y, por lo tanto, tienen un manejo más complejo cuando se habla de sus operaciones. Tenga en cuenta que una string con espacios es en realidad una string vacía pero tiene un tamaño distinto de cero. Este artículo también discutió ese problema y su solución. 
Veamos diferentes métodos para verificar si la string está vacía o no.
Método #1: Usar len() 
Usar len() es el método más genérico para verificar una string de longitud cero. Aunque ignora el hecho de que una string con solo espacios también debería considerarse prácticamente como una string vacía, incluso si no es cero.
 

Python3

# Python3 code to demonstrate
# to check if string is empty
# using len()
 
# initializing string
test_str1 = ""
test_str2 = "  "
 
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(len(test_str1) == 0):
    print ("Yes")
else :
    print ("No")
 
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(len(test_str2) == 0):
    print ("Yes")
else :
    print ("No")

Producción : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No

 
Método n.º 2: Usar not 
not operator también puede realizar una tarea similar a len(), y verifica la string de longitud 0, pero al igual que la anterior, considera que la string con solo espacios tampoco está vacía, lo que prácticamente no debería ser cierto. 
 

Python3

# Python3 code to demonstrate
# to check if string is empty
# using not
 
# initializing string
test_str1 = ""
test_str2 = "  "
 
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(not test_str1):
    print ("Yes")
else :
    print ("No")
 
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(not test_str2):
    print ("Yes")
else :
    print ("No")

Producción : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No

  
Método n.º 3: usar not + str.strip() 
El problema de la string de longitud vacía + cero puede eliminarse posiblemente usando strip(), strip() devuelve verdadero si encuentra los espacios, por lo tanto, verificarlo puede resolver el problema de buscar una string puramente vacía. 
 

Python3

# Python3 code to demonstrate
# to check if string is empty
# using not + strip()
 
# initializing string
test_str1 = ""
test_str2 = "  "
 
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(not (test_str1 and test_str1.strip())):
    print ("Yes")
else :
    print ("No")
 
# prints Yes
print ("The zero length string with just spaces is empty ? : ", end = "")
if(not(test_str2 and test_str2.strip())):
    print ("Yes")
else :
    print ("No")

Producción : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes

 
Método #4: Usar not + str.isspace 
Funciona de manera similar al método anterior y verifica los espacios en la string. Este método es más eficiente porque, strip() requiere realizar la operación de eliminación también, lo que requiere cargas de cálculo, si no. de espacios son de buen número. 
 

Python3

# Python 3 code to demonstrate
# to check if string is empty
# using not + isspace()
 
# initializing string
test_str1 = ""
test_str2 = "  "
 
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(not (test_str1 and not test_str1.isspace())):
    print ("Yes")
else :
    print ("No")
 
# prints Yes
print ("The zero length string with just spaces is empty ? : ", end = "")
if(not (test_str2 and not test_str2.isspace())):
    print ("Yes")
else :
    print ("No")

Producción : 
 

The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *