[Solved] Remove quotes from list items without making it a string


You may use below list comprehension using map with eval(...) as:

import ast

Users = ['Protein("SAHDSJDSFJH"), {"id": "s1"}',
         'Protein("ACGTWZJSFNM"), {"id": "s2"}',
         'Protein("ABHZZEQTAAB"), {"id": "s3"}']

new_list = [y for x in map(eval, Users) for y in x]

where new_list will hold the value:

[Protein("SAHDSJDSFJH"), {'id': 's1'}, 
 Protein("ACGTWZJSFNM"), {'id': 's2'}, 
 Protein("ABHZZEQTAAB"), {'id': 's3'}]

PS: Note that there should exists a class definition Protein in the scope whose __init__ expects one string variable as an argument, and __repr__ function to display the Protein‘s object in the format you require . For example:

class Protein:
    def __init__(self, x):
        self.x = x

    def __repr__(self):
        return 'Protein("%s")' % self.x

Note: Usage of eval in Python code is not a good practice. You should not be using it for the live application, however it is fine to use it for home-work (if that’s the case). Take a look at: Why is using ‘eval’ a bad practice? for the details.

Edit: Based on the comment by the OP. Instead of using:

users.append('Protein (" ' +dsspSeqList[i]+ ' ", {"id" : "s' +str(i +1)+ ' "}) ')

you should be using:

users.append(Protein(dsspSeqList[i], {"id" : "s{}".format(i +1)}))

This way you don’t need a eval function. But Note part will still be applicable.

5

solved Remove quotes from list items without making it a string