I have an idea for a fix where I do another for loop, get each character, and append each non-comma to another array and then convert to int. But this sounds complex…
You're right—that would work, but it's not the easiest way to do it.
Just use the split
method on strings, like this:
for line in info:
solution.append(line.split(","))
Now, instead of each line being ['1234,123,345\n']
, it will be ['1234', '123', '345\n']
.
This gets you close, but those are still strings, not ints. An inner loop to convert each one to an int, just as you suggested, will work great. But it might be easier to read with a for loop in a list comprehension, rather than in a for statement. Like this:
for line in info:
solution.append([int(number) for number in line.split(",")])
If you don't understand the comprehension, here it is as a statement:
for line in info:
numbers = []
for number in line.split(","):
numbers.append(int(number))
solution.append(numbers)
And, since the int
function can ignore whitespace, int('345\n')
is 345
, so you don't have to do anything else.
But if you did have to do something else, rstrip
would be the easiest answer: it removes all whitespace from the end of a string. So:
for line in info:
solution.append([int(number) for number in line.rstrip().split(",")])