Python: "1-2-3-4" to [1, 2, 3, 4]
What is the best way to convert a formatted string to a "1-2-3-4"
list [1, 2, 3, 4]
? The string can also be empty, in which case the conversion must return an empty list []
.
This is what I have:
map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
EDIT: Sorry to all those who answered, before I fixed my question, it was unclear for the first minute or so.
source to share
From the format of your example, you want int in a list. If so, you will need to convert strings to int. If not, then you are done after splitting the line.
text="1-2-3-4"
numlist=[int(ith) for ith in text.split('-')]
print numlist
[1, 2, 3, 4]
textlist=text.split('-')
print textlist
['1', '2', '3', '4']
EDIT: Revising my answer to reflect the update in the question.
If the list might be garbled then "try ... catch" if your friend. This will ensure that the list is either built or you get an empty list.
>>> def convert(input):
... try:
... templist=[int(ith) for ith in input.split('-')]
... except:
... templist=[]
... return templist
...
>>> convert('1-2-3-4')
[1, 2, 3, 4]
>>> convert('')
[]
>>> convert('----1-2--3--4---')
[]
>>> convert('Explicit is better than implicit.')
[]
>>> convert('1-1 = 0')
[]
source to share