Reputation: 13
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 the numbers to an empty string and convert them to an int when there was a space. Here's the code.
n is the length of the string of numbers num is the empty string I add the numbers to. Originally num=""
while i<n:
if temps[i]!=' ':
num=num+temps[i]
elif temps[i]==' ':
print type(num)
x=int(num)
The problem is that when it runs I get an error for the line with x=int(num) saying
ValueError: invalid literal for int() with base 10: ''
when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask.
Thanks
Upvotes: 1
Views: 182
Reputation: 10951
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]
Upvotes: 1
Reputation: 31662
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.
Upvotes: 1
Reputation: 6703
You should try to split the task into 2 subtasks:
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.
Upvotes: 0
Reputation: 7160
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
Upvotes: 1
Reputation: 5433
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()]
Upvotes: 6