1

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

0

5 Answers 5

6

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

1 Comment

Yup, exactly what I was writing :)
1

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

Comments

1

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.

Comments

1

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]

Comments

0

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.

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.