I have a string '[1. 2. 3. 4. 5.]' and I would like to convert to get only the int such that i obtain an array of integer of [1, 2, 3, 4, 5]
How do I do that? I tried using map but unsuccessful.
Use strip for remove [], split for convert to list of values which are converted to int in list comprehension:
s = '[1. 2. 3. 4. 5.]'
print ([int(x.strip('.')) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
Similar solution with replace for remove .:
s = '[1. 2. 3. 4. 5.]'
print ([int(x) for x in s.strip('[]').replace('.','').split()])
[1, 2, 3, 4, 5]
Or with convert to float first and then to int:
s = '[1. 2. 3. 4. 5.]'
print ([int(float(x)) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
Solution with map:
s = '[1. 2. 3. 4. 5.]'
#add list for python 3
print (list(map(int, s.strip('[]').replace('.','').split())))
[1, 2, 3, 4, 5]