Function to clean trailing and or preceeding whitespace from string types in complex list, dictionary, and tuple structures. This is a recursive function to allow for complete coverage of all items in the structure. Wanted to share it as I needed it and after searching for a while I gave up and wrote one.
For example a = ["\rText \r\n", "This one is fine", ["stuff ", [" Something Else"], 4, "Another ", "one", " with"], "\twhitespace\r\n"]
print cleanWhiteSpace(a) Result: ["Text", "This one is fine", ["stuff", ["Something Else"], 4, "Another", "one", "with"], "whitespace"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import types
def cleanWhiteSpace(obj):
objType = type(obj)
if(objType is types.StringType): # String
# Clean regular string
return obj.lstrip().rstrip()
elif((objType is types.ListType) or (objType is types.TupleType)): # List or Tuple
out = []
for ele in obj: # Iterate the elements
out.append(cleanWhiteSpace(ele)) # Recurse into this function for the element
return out
elif(objType is types.DictType): # Dictionary
out = {}
for ele in obj: # Iterate the elements
out[ele] = cleanWhiteSpace(obj[ele]) # Recurse into this function for the element
return out
else:
# Non String or list object return it
return obj
|
A few recommendations:
Putting all that together, I'd recommend the following rewrite:
(n.b. that it does not recurse to dictionary keys -- this is to be consistent with your version. Obviously, it would be easy to change it to do so.)
Taking the previous recommendation as an example, you could go a step further in abstracting the functionality to work with any object and operation.
To use this to accomplish the original task of cleaning whitespace: