Problem statement:
I am trying to read lines from my data and and output both the forward
and reverse
orientation by passing my list to a function. To solve what I am trying to do, I have to pipe the function-name as string
. I am making a mock test below that replicates my original problem in a simple way.
my_str = 'abcdef\nijklmn\nstuv\n'
my_str = my_str.rstrip('\n').split('\n')
for lines in my_str:
print(lines)
line_list = list(lines)
# I want to read both forward and reverse orientation using a function "(def orient_my_str():"
# the reason to pass this into another function is because I have lots of data crunching to do in each orientation (not shown here).
# but, below process typically resolves what I am trying to achieve
line_rev = orient_my_str(line_list, orientation='reversed')
line_fwd = orient_my_str(line_list, orientation='')
print('list in reverse orientation :', line_rev)
print('list in forward orientation :', line_fwd)
print()
# I am only want to make one function not two, because if I make two functions ..
# .. I will have to copy a large amount of code below the for-loop.
# there should be a way to fix this problem (calling function using string name when required and not).
def orient_my_str(line, orientation):
my_output = ''
for item in eval(orientation)(line):
my_output += item
print(my_output)
return my_output
# But, this only works for reverse orientation. I know the issue is with passing "eval('')(line)" but was hoping it would work.
I tried to fix my code using ideas from these links,
Use a string to call function in Python
Calling a function of a module by using its name (a string)
python function call with variable
but I cannot seem to work it out.