I get the correct output with that code. How exactly are you running it?
My bad, I never properly removed the newline characters as I am using a real dataset (a file), as opposed to a constructed one as in the example I gave. Thanks for your patience and guidance.