Reputation: 349
I have a list like this
countries = ["['Luxemburgo ", 'Suiza ', 'Noruega ', 'Irlanda ', 'Islandia ', 'Catar ', 'Singapur ', 'Estados Unidos ', 'Dinamarca ', 'Australia ', 'Suecia ', 'Países Bajos ', 'San Marino ', 'Austria ', 'Finlandia ', 'Alemania ', 'Hong Kong ', 'Bélgica ', 'Canadá ', 'Emiratos Árabes Unidos ', 'Reino Unido ', 'Israel ', 'Nueva Zelanda ', 'Francia ', "Japón ']"]
and I don't know how to convert it to a really list. If I print the first element:
>>> print(countries[0])
['Luxemburgo
How can I do to eliminate the [ and it would have the two '' because it's a string but with the rest of the words in the list that prints only the word without the ''.
Upvotes: 1
Views: 85
Reputation: 27283
The better question is: Where did the list come from and can we fix the problem at the source?
But you can fix it now by doing:
import ast
countries_fixed = ast.literal_eval("', '".join(countries))
Afterwards, your list elements still contain spaces, to fix that too, you can do this instead:
countries_fixed = ast.literal_eval(
"', '".join(country.strip() for country in countries)
)
Result:
>>> print(countries[0])
Luxemburgo
Upvotes: 1
Reputation: 3010
you can simply do like this:
countries = ["['Luxemburgo ", 'Suiza ', 'Noruega ', 'Irlanda ', 'Islandia ', 'Catar ', 'Singapur ', 'Estados Unidos ', 'Dinamarca ', 'Australia ', 'Suecia ', 'Países Bajos ', 'San Marino ', 'Austria ', 'Finlandia ', 'Alemania ', 'Hong Kong ', 'Bélgica ', 'Canadá ', 'Emiratos Árabes Unidos ', 'Reino Unido ', 'Israel ', 'Nueva Zelanda ', 'Francia ', "Japón ']"]
lis=[]
for x in countries:
lis.append(x.replace("['","").replace("']",""))
print(lis[0])
output:
Luxemburgo
Upvotes: 0