Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python how do I split a string into multiple integers?

I'm reading a string which is always five numbers separated by a space, I want to split this up into five individual integers so that I can process them separately.

so far I have:

reader = csv.reader([data.data], skipinitialspace=True)
for r in reader:
    print r

which allows me to print the values out, how do I store them as individual integers?

like image 610
ianphil397 Avatar asked Dec 06 '22 09:12

ianphil397


1 Answers

You could do it like this. Assuming s is your line from reader.

>>> s='2 3 4 5 6'
>>> s.split(' ')
['2', '3', '4', '5', '6'] #just split will give strings
>>> [int(i) for i in s.split(' ')] #typecasting to ints
[2, 3, 4, 5, 6] #now you have ints

A word of caution though, I am assuming there is no other data type in the line from reader. Otherwise this code has potential to crash. You can of course put try: except: to circumvent that or use more fine-tuned parsing techniques.

UPDATE 0: Brilliant one liner from @Pavel Annosov - map(int, s.split()). map is a nifty python in-built function which lets you map a function to any iterable.

UPDATE 1: Its fairly simple to see how this will work. but to make it even more clear to @user2152165

ints_list = []
for r in reader:
    ints_list = map(int, r.strip().split(' '))

ints_list has a list of your ints. do what you want with it...

like image 117
Srikar Appalaraju Avatar answered Dec 17 '22 14:12

Srikar Appalaraju