Need some advice on how to refactoring this kind of code, as you can see, the basic code for all, left, right is the same, all what is changing is .strip(), .lstrip(), .rstrip(), is it possible to refactor this in a "beautiful" manner?
def clean_whitespaces(input, mode='all', ):
result = None
modes = (None, 'all', 'left', 'right')
if mode not in modes:
raise ValueError('clean_whitespaces: mode must be one of {}.'.format(modes))
if mode == None:
mode = 'all'
if mode == 'all':
if isinstance(input, str):
result = input.strip()
else:
input = list(input)
result = [entry.strip() for entry in input]
return result
elif mode == 'left':
if isinstance(input, str):
result = input.lstrip()
else:
input = list(input)
result = [entry.lstrip() for entry in input]
return result
elif mode == 'right':
if isinstance(input, str):
result = input.rstrip()
else:
input = list(input)
result = [entry.rstrip() for entry in input]
return result
inputreally shouldn't be used as a name for anything, it is a built-inentry.strip) or the names of them (e.g.'strip') which can then be looked up usinggetattr.