Reputation: 11
I take such an input from the user-
Then i try to split it using comma and append it into a list as numbers.
But whenever I do so , it gives out an error and the only stores "20,340,2".
Notice how the last number for the first line is 223, however, my list only stores 2 and ignores the 23 at the end, even though i've used comma to separate the elements. Same for 789 as well (next line). It stops at 78 and ignores the 9 below, although it is the same number Can somebody please help me take a such inputs and separates each element properly using commas and stores it in a list as numbers? Thank you.
Upvotes: 0
Views: 57
Reputation: 2052
If in fact this is coming from an input file that you read it would look like:
input = '120,340,2\n 23,456,678,78\n 9,456'
when read.
This results in a number of different problems. One of which is that you have read until the second delimiting single quote to make it work.
Then you get something like:
input = '120,340,2\n 23,456,678,78\n 9,456'
input = input.replace(" ","")
input = input.replace("\n","")
Upvotes: 1
Reputation: 82
Like this?
input='120,340,200,240,21,2,9,5,300'
input.replace(" ","") #removes spaces
input_array=input.split(",") #creates array, although they are still strings
for i in range(len(input_array)): #for every number in the list, replace the string with the number.
input_array[i]=int(input_array[i])
print(input_array)
Upvotes: 2
Reputation: 51037
If you really want to allow numbers with spaces in them, you could start by just removing all spaces from the string:
>>> s = '120,340,2 23,456,678,78 9,456'
>>> s.replace(' ', '')
'120,340,223,456,678,789,456'
From there, you can split on commas and parse the parts as numbers.
Upvotes: 2