Python: remove double quotes from a list

Asked

Viewed 991 times

2

Gentlemen(as), I need remove double quotes from each index in the list and, would like to remove each empty space, as well as remove that ' n' from the end of the list.

lista = ['"11/07/2019"', '"00:58:40"', '"087974440345"', '""', '"Cancelamento automático"\n', '""\n']

If I use:

print(''.join(lista).replace('"', "'"))

The result will not be as desired. The result will be (in two lines):

'11/07/2019''00:58:40''087974440345''''Cancelamento automático'
''

I need to maintain the list structure, with commas separating each term from the list, because I will do other tasks with this list.

Can you help me? Thank you.

1 answer

5


Not need to convert to string with .join() and use eval() for that is a exaggeration, Python has functionality and internal Apis that solve many things well, in your case just make a for to process all data.

To remove the \n can use .replace() within the is same and for the " you need to remove only the limits of the string, in this case you can use .strip(), example:

lista = ['"11/07/2019"', '"00:58:40"', '"087974440345"', '""', '"Cancelamento automático"\n', '""\n']

lista = [value.replace('\n', '').strip('"') for value in lista]

print(lista)

Returning:

['11/07/2019', '00:58:40', '087974440345', '', 'Cancelamento automático', '']

Basically a new list was created with the values treated, so within [...] we have:

  • The value that will be treated and added to the new list value.replace('\n', '').strip('"')
  • What reads item by item from the list: for value in lista

Also note that in the result some items are empty strings, in this case you can use filter() to remove, returning:

['11/07/2019', '00:58:40', '087974440345', 'Cancelamento automático']

Now if you want to filter the values just pass the condition after the for, Suppose you want to ignore the empty items, do so:

lista = ['"11/07/2019"', '"00:58:40"', '"087974440345"', '""', '"Cancelamento automático"\n', '""\n']

lista = list(filter(lambda value: value != '', [value.replace('\n', '').strip('"') for value in lista]))

print(lista)

Maybe you’re not very pretty to look at, so if you prefer you can do it too:

lista = ['"11/07/2019"', '"00:58:40"', '"087974440345"', '""', '"Cancelamento automático"\n', '""\n']

relista = []

for value in lista:
    value = value.replace('\n', '').strip('"')

    if value != '':
        relista.append(value)

print(relista)

Here in this example we have already dealt with and checked with the if if it is an empty item, if you want to remove the empty values, if it is not the case, adjust to:

relista = []

for value in lista:
    relista.append( value.replace('\n', '').strip('"'))

print(relista)
  • 1

    William, thank you for your full and well explained reply. I understood and I will study each case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.