Skip to content Skip to sidebar Skip to footer

Troubles Converting From String To Int Python

I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ('2 -5 7 8 10 -205') What I tried to do was add t

Solution 1:

Use str.split() to split your string at spaces, then apply int to every element:

s = '2 -5 7 8 10 -205'nums = [int(num) for num in s.split()]

Solution 2:

If your string looks like this:

s = '2 -5 7 8 10 -205'

You can create a list of ints by using a list comprehension. First you will split the string on whitespace, and parse each entry individually:

>>> [int(x) for x in s.split(' ')]
[2, -5, 7, 8, 10, -205] ## list of ints

Solution 3:

You could do this with a list comprehension:

data = ('2 -5 7 8 10 -205')
l = [int(i) for i in data.split()]
print(l)
[2, -5, 7, 8, 10, -205]

Or alternatively you could use the map function:

list(map(int, data.split()))
[2, -5, 7, 8, 10, -205]

Benchmarking:

In [725]: %timeit list(map(int, data.split()))
100000 loops, best of 3: 2.1 µs per loop

In [726]: %timeit [int(i) for i in data.split()]
100000 loops, best of 3: 2.54 µs per loop

So with map it works faster

Note: list is added to map because I'm using python 3.x. If you're using python 2.x you don't need that.

Solution 4:

Built-in method would do the job as well:

>>>s = '2 -5 7 8 10 -205'>>>map(int, s.split())
[2, -5, 7, 8, 10, -205]

If Python 3+:

>>>s = '2 -5 7 8 10 -205'>>>list(map(int, s.split()))
[2, -5, 7, 8, 10, -205]

Solution 5:

You should try to split the task into 2 subtasks:

  1. Split the numbers in the string into list of numbers using split
  2. Convert each of the strings in the list to a regular integer using map map

As a general advise - you should also read the documentation so that you can figure out how much of the hard work could be saved by just chaining the output of one function as an input of the next function.

Post a Comment for "Troubles Converting From String To Int Python"