arr.rsplit(',', len(arr))
print sum(arr)
If I input the string of "1,2,3,4", the first line splits it in a list of 1,2,3,4. But when I print the sum it does not work I get an error message.
See Question&Answers more detail:osarr.rsplit(',', len(arr))
print sum(arr)
If I input the string of "1,2,3,4", the first line splits it in a list of 1,2,3,4. But when I print the sum it does not work I get an error message.
See Question&Answers more detail:osIn your case your splitting the string but the result is not assigned again to arr
so your variable arr
value is not getting changed it remains the string, so while you apply sum(arr)
it is giving an error. But if you assign it to arr the type of split elements is <class 'str'>
so convert it into integer
I trying to use split
instead of rsplit
Solution in Python 3 :
arr = "1,2,3,4"
arr = map(int,arr.split(','))
print(sum(arr))
Output : 10
It will convert each element to integer and then take the sum. But if you try to print arr : print(arr)
after the map method it gives output : <map object at 0x7f90c081acc0>
So convert arr
to list
to access the elements So instead of arr = map(int,arr.split(','))
give arr = list(map(int,arr.split(',')))
If you want to use rsplit
then Solution (in python 3):
arr = "1,2,3,4"
arr = list(map(int,arr.rsplit(',', len(arr))))
print(sum(arr))