SoFunction
Updated on 2024-11-15

How Python Gracefully Removes Empty Characters and None Elements from a List of Characters

A piece of code like this removes the empty string:

def not_empty(s):
  return s and ()
print(list(filter(not_empty, ['A', '', 'B', None,'C', ' '])))

  The code is very simple, the effect, you can throw to Python online tools | run to see, very nice ~ but not_empty function return value is a bit complicated, you can carefully analyze it:

  • - Suppose the strings a and b are used for the AND operation a and b:
  • - If both are nonempty, then a and b = b;
  • - If both are not None and at least one is null, i.e. '', then a and b = ''
  • - If at least one is equal to None, then a and b = None

  Since the strip() function itself operates on str types, using a separate return () when s = None will result in a " 'NoneType' object has no attribute 'strip'" error;

  However, if you can guarantee that s[] does not contain a None member, the function can actually be written directly as

def not_empty(s):
  return ()
print(list(filter(not_empty, ['A', '', 'B', 'C', ' '])))

  Thus, return s and () serves to exclude the case where s = None, not to exclude the case where s = '' or s = ' '.

  But why doesn't return s and () report an error when s = None? The reason is that the and operation terminates early if there is a single argument to the and operation that cannot possibly make and true, and because python is an interpreted language, it checks as it goes along and finishes the sentence before it gets to the () in s and () (a false positive), so it won't report an error.

  Finally, the above program can be further encapsulated with a lambda expression.

def str_Nempty(s):
	return list(filter(lambda s: s and (),s))
print(str_Nempty(['A', '', 'B', 'C', ' ']))

This is the whole content of this article, I hope it will help you to learn more.