Lau
Lau

Reputation: 35

Remove double quotes and special characters from string list python

I'm pretty new in python.

I have a list like this:

['SACOL1123', "('SA1123', 'AAW38003.1')"]
['SACOL1124', "('SA1124', 'AAW38004.1')"]

And I want to remove the extra double quotes and paranthesis, so it looks like this:

['SACOL1123', 'SA1123', 'AAW38003.1']
['SACOL1124', 'SA1124', 'AAW38004.1']

This is what I managed to do:

newList = [s.replace('"(', '') for s in list]
newList = [s.replace(')"', '') for s in newList]

But the output is exactly like the input list. How can I do it?

Upvotes: 0

Views: 298

Answers (2)

Vidya P V
Vidya P V

Reputation: 481

This can be done by converting each item in the list to a string and then substituting the punctuation with empty string. Hope this helps:

import re

List = [['SACOL1123', "('SA1123', 'AAW38003.1')"], 
        ['SACOL1124', "('SA1124', 'AAW38004.1')"]]

New_List = []
for Item in List:
    New_List.append(re.sub('[\(\)\"\'\[\]\,]', '', str(Item)).split())

New_List
Output: [['SACOL1123', 'SA1123', 'AAW38003.1'], 
         ['SACOL1124', 'SA1124', 'AAW38004.1']]

Upvotes: 1

Austin
Austin

Reputation: 26039

This is possible using ast.literal_eval. Your second element from list is string representation of a valid Python tuple which you can safely evaluate.

[[x[0]] + list(ast.literal_eval(x[1])) for x in lst]

Code:

import ast

lst = [['SACOL1123', "('SA1123', 'AAW38003.1')"],
       ['SACOL1124', "('SA1124', 'AAW38004.1')"]]

output = [[x[0]] + list(ast.literal_eval(x[1])) for x in lst]

# [['SACOL1123', 'SA1123', 'AAW38003.1'],
#  ['SACOL1124', 'SA1124', 'AAW38004.1']]

Upvotes: 1

Related Questions