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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With