How do i make something like
x = \'1 2 3 45 87 65 6 8\'
>>> foo(x)
[1,2,3,45,87,65,6,8]
I\'m completely stuck, if i do it by inde
The most simple solution is to use .split()
to create a list of strings:
x = x.split()
Alternatively, you can use a list comprehension in combination with the .split() method:
x = [int(i) for i in x.split()]
You could even use map map
as a third option:
x = list(map(int, x.split()))
This will create a list
of int
's if you want integers.
Assuming you only have digits in your input, you can have something like following:
>>> x = '1 2 3 45 87 65 6 8'
>>> num_x = map(int, filter(None, x.split(' ')))
>>> num_x
[1 2 3 45 87 65 6 8]
This will take care of the case when the digits are separated by more than one space character or when there are space characters in front or rear of the input. Something like following:
>>> x = ' 1 2 3 4 '
>>> num_x = map(int, filter(None, x.split(' ')))
>>> num_x
[1, 2, 3, 4]
You can replace input to x.split(' ')
to match other delimiter types as well e.g. ,
or ;
etc.
A simple line can be...
print (map(int, x.split()))
As some one wisely corrected me, in python >=3, it shall become,
print(list(map(int,x.split())))
It can also be user in earlier versions.
Having input with space at beginning or end of the string or delimited with multiple uneven amount of spaces between the items as above, s.split(' ') returns also empty items:
>>> s=' 1 2 3 4 67 8 9 '
>>> list(s.split(' '))
['', '1', '2', '', '3', '4', '67', '8', '9', '']
I's better to avoid specifying a delimiter:
>>> list(s.split())
['1', '2', '3', '4', '67', '8', '9']
If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed).
If you want to split only at spaces, empty strings can be easily filtered:
>>> [item for item in s.split(' ') if item]
['1', '2', '3', '4', '67', '8', '9']
Just to make a clear explanation.
You can use the string method str.split()
which split the string into a list. You can learn more about this method here.
Example:
def foo(x):
x = x.split() #x is now ['1','2','3','45', ..] the spaces are removed.
for i, v in enumerate(x): #Loop through the list
x[i] = int(v) #convert each element of v to an integer
That should do it!
>>> x
[1, 2, 3, 45, 87, 65, 6, 8]
No need to worry, because python provide split() function to change string into a list.
x='1 2 3 4 67 8 9'
x.split()
['1', '2', '3', '4', '67', '8']
or if you want output in integer form then you can use map function
map(int ,x.split(' '))
[1, 2, 3, 4, 67, 8]