Home>

### convert -3 from string to python list

The input is the string '0 -3 1'.
When I try to bring her to the list, it turns out this`a= ['0', '-', '3', '1']`.
I need it to look like`a= [0, -3.1]`.

My code:

``````a= list (input ())
a.remove ('')
a.remove ('')
print (a)
``````

Spatz2021-10-14 02:45:11

a= list (input ()) a.remove ('') a.remove ('') print (a)

Boris Bandit2021-10-14 02:45:11

Insert the code into the question by clicking the "edit" button

Spatz2021-10-14 02:45:11

Here's an option -a= list (map (int, input (). Strip (). Split ()))

GrAnd2021-10-14 02:45:11

input () returns a string, and a simple casting of a string into a list (list ()) splits the string letter by letter (the same happens if you treat a string like a list: slice str [5: 8], bypass for c in str, etc).

as you correctly suggested in the comments, you need to split the line by spaces:

``````input (). split ()
``````

but there may be a newline or a space at the end of the line, so first remove them:

``````input (). strip (). split ()
``````

is now a list of strings, like`['0', '-3', '1']`,
Let's make numbers out of them: you need to apply int () to each element of the array, this is what map does:

``````map (int, input (). strip (). split ()))
``````

well, since map () returns an iterator, let's make a list out of it

``````list (map (int, input (). strip (). split ()))
``````

input () returns a string, and a simple casting of a string into a list (list ()) splits the string letter by letter (the same happens if you treat a string like a list: slice str [5: 8], bypass for c in str, etc).

as you correctly suggested in the comments, you need to split the line by spaces:

``````input (). split ()
``````

but there may be a newline or a space at the end of the line, so first remove them:

``````input (). strip (). split ()
``````

is now a list of strings, like`['0', '-3', '1']`,
Let's make numbers out of them: you need to apply int () to each element of the array, this is what map does:

``````map (int, input (). strip (). split ()))
``````

well, since map () returns an iterator, let's make a list out of it

``````list (map (int, input (). strip (). split ()))
``````