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.
jezrael
868k103 gold badges1.4k silver badges1.3k bronze badges
1 Answer 1
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]
answered May 29, 2017 at 13:08
jezrael
868k103 gold badges1.4k silver badges1.3k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py