Examples of how to convert a string in a list in python:
Change a string representation of a list into a list
To convert a string representation of a list into a list in python, a solution is to use ast.literal_eval, illustration:
>>> s = '[1,2,3,4]'>>> type(s)<class 'str'>>>> import ast>>> l = ast.literal_eval(s)>>> type(l)<class 'list'>>>> l[1]2
Put all string elements into a list:
Example of how to put all string elements into a list using the "list comprehension" approach:
>>> s = 'Salut, comment ca va ?. Bien, et toi ?.'>>> l = [i for i in s]>>> l['S', 'a', 'l', 'u', 't', ',', ' ', 'c', 'o', 'm', 'm', 'e', 'n', 't', ' ', 'c', 'a', ' ', 'v', 'a', ' ', '?', '.', ' ', 'B', 'i', 'e', 'n', ',', ' ', 'e', 't', ' ', 't', 'o', 'i', ' ', '?', '.']
Put elements separated by a space in a list
To put elements separated by a space in a list under python, a solution is to use the built-in python function called split(), example:
>>> s = 'Salut, comment ca va ?. Bien, et toi ?.'>>> l = s.split()>>> l['Salut,', 'comment', 'ca', 'va', '?.', 'Bien,', 'et', 'toi', '?.']
Put elements separated by a coma in a list
To put elements separated by a coma in a list under python, a solution is to use the built-in python function called split(), example:
>>> l = s.split(',')>>> l['Salut', ' comment ca va ?. Bien', ' et toi ?.']
Put elements separated by a point in a list
To put elements separated by a point in a list under python, a solution is to use the built-in python function called split(), example:
>>> l = s.split('.')>>> l['Salut, comment ca va ?', ' Bien, et toi ?', '']
Note: remove elements from the list
Note: to remove elements from the list (example remove the coma):
>>> [i.replace(',','') for i in l]['Salut comment ca va ?', ' Bien et toi ?', '']
References
| Links | Site |
|---|---|
| split() | python doc |
| Python String replace() Method | tutorialspoint |
| Converting a string representation of a list into an actual list object | stackoverflow |
| ast — Abstract Syntax Trees | python doc |
