pythonstringlistdouble-quotessingle-quotes

How to remove quotes from list of strings and store it as list again..?


I have to call the function in a for loop. All those functions are stored in a list as a string with quotes. I need to remove those quotes and store the values again in a list.

What needs to be done:

  1. Fetch the function list from DB
  2. Remove single/double quotes from a list of strings
  3. Store those strings in a list
  4. Loop the list to execute functions

Python

fruits = ['apple','mango','orange']
print(type(fruits))
func = '[%s]'%','.join(map(str,fruits))
print(func) ## [apple,mango,orange]
print(type(func))

def apple():
  print("In apple")
def mango():
   print("In mango")
def orange():
   print("In orange")

n = len(func)
func_it = itertools.cycle(func)
for i in range(n):
   next(func_it)()

Output

<class 'list'>
[apple,mango,orange]
<class 'str'>

After removing the quotes from the strings, Its data type is getting changed to . Is there any way to remove quotes from a list of strings and store those values as a list again?


Solution

  • You can use the built in python exec() function that will execute any string as code.

    #!/usr/bin/env python3
    
    fruits = ['apple','mango','orange']
    
    def apple():
      print("In apple")
    def mango():
       print("In mango")
    def orange():
       print("In orange")
    
    for func in fruits:
        exec(func + '()')  
    

    Output

    In apple
    In mango
    In orange