Convert a string containing integers to list of integers

7

What is the shortest way to convert a string containing integers separated by spaces to a list of integers?

  • input : "-3 1 5 8 10"
  • output : [-3, 1, 5, 8, 10]

I regularly face this situation and I wanted to know if there is a better way than (24 bytes):

list(map(int,s.split()))

Nelson G.

Posted 2019-06-19T16:32:18.583

Reputation: 317

Answers

12

Using map is way shorter than any of the ways I mentioned. You should do that.

Instead of calling list(...), you should use [*...] (21 bytes):

[*map(int,s.split())]

Or even better, if you switch to python 2, map will always return a list. (18 bytes):

map(int,s.split())

Try it online!

Original Post:


The straightforward way is going to be 26 bytes

[int(n)for n in s.split()]

Try it online!

However, if a tuple is acceptable instead of a list, we could use a trick to shave one byte off leaving us with 25 bytes

eval(",".join(s.split()))

Try it online!

This can be shortened even more with the replace function (24):

eval(s.replace(' ',','))

Try it online!

and even more with iterable unpacking (22):

eval(s.replace(*" ,"))

Try it online!

If you truly need a list, you can wrap it in [*...]. This is still shorter than the straightforward way by 1 byte:

[*eval(s.replace(*" ,"))]

James

Posted 2019-06-19T16:32:18.583

Reputation: 54 537