Python: formas de eliminar múltiples espacios vacíos de la lista de strings

A veces, mientras trabajamos con strings de Python, tenemos un problema en el que necesitamos realizar la eliminación de espacios vacíos en Strings. El problema de filtrar un solo espacio es más fácil. Pero a veces no somos conscientes de la cantidad de espacios. Esto tiene aplicación en muchos dominios. Analicemos ciertas formas en que se puede realizar esta tarea. Método #1: Usando loop + strip() Esta es una forma en la que podemos realizar esta tarea. En esto, eliminamos las strings usando strip(), se reduce a un solo espacio y luego se puede probar el valor NULL. Devuelve True si la string es un espacio simple y, por lo tanto, ayuda en el filtrado. 

Python3

# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
 
# initializing list
test_list = ['gfg', '   ', ' ', 'is', '            ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
    if ele.strip():
        res.append(ele)
     
# printing result
print("List after filtering non-empty strings : " + str(res))
Producción : 

The original list is : ['gfg', '   ', ' ', 'is', '            ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

  Método n.º 2: Uso de la comprensión de listas + strip() La combinación de las funciones anteriores también se puede usar para realizar esta tarea. En esto, empleamos un enfoque de una sola línea para realizar esta tarea en lugar de usar el bucle. 

Python3

# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
 
# initializing list
test_list = ['gfg', '   ', ' ', 'is', '            ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
res = [ele for ele in test_list if ele.strip()]
     
# printing result
print("List after filtering non-empty strings : " + str(res))
Producción : 

The original list is : ['gfg', '   ', ' ', 'is', '            ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Método #3: Usando find()

Python3

# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using find()
 
# initializing list
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using find()
res = []
for ele in test_list:
    if ele.find(' ')==-1:
        res.append(ele)
     
# printing result
print("List after filtering non-empty strings : " + str(res))
Producción

The original list is : ['gfg', ' ', ' ', 'is', '\t\t ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

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 *