0

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.

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.