-1

I have some code that takes numbers separated by spaces from input(). I tried to call .split() on it but for some reason it turns [56 78 90 1 2 3] into [78.0, 90.0, 1.0, 2.0]. Thanks

def insert(self, lst):
    for x in lst.split():
        try:
            self.theList.append(float(x))
        except:
            3+4
Ecoturtle
  • 445
  • 1
  • 4
  • 7
  • what are you expecting with the `float` function? Perhaps you mean to use the `int` function – logee Feb 08 '16 at 03:14
  • You are explicitly [casting x as a float](https://docs.python.org/3/library/functions.html#float) (`float(x)`) – LinkBerest Feb 08 '16 at 03:14

3 Answers3

1

"some reason" is that you're calling float which converts the value to float type.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0

It does this because you're using float(x). Use an integer value if all of your numbers will be integers. Otherwise, you can expect additional decimal places when using the float function.

MelanieG
  • 11
  • 2
0

You start out with the string lst = "[56 78 90 1 2 3]". It is split by whitespaces giving ['[56', '78', '90', '1', '2', '3]']. Notice the brackets in the first and last element!

You then interpret each element as a float which fails on float('[56') and float('3]'), causing the program to enter the except case that you carefully chose to not utilize.

Here is how you would turn an integer string into a proper list that could be iterated over, so that you could reinterpret the numbers as floats for whatever reason you would want that:

import ast
ast.literal_eval(lst.replace(" ", ", ")

Why are you passing around a bunch of integers as a string anyway? Could you show the place in your code where "[56 78 90 1 2 3]" comes into existence?

Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
  • 1
    Why would you suggest using a literal_eval (at least it is ast) when [there are so many other, better, options for this](http://stackoverflow.com/questions/1614236/in-python-how-to-i-convert-all-items-in-a-list-to-floats)? – LinkBerest Feb 08 '16 at 03:43
  • I chose `literal_eval()` because the input was already in string format. Replacing the brackets in `'[56'` either by `replace()` or by sub-scripting just seems like a more roundabout way. – Harald Nordgren Feb 08 '16 at 09:21