[Tutor] Coma separated instead TAB separated
alan.gauld at btinternet.com
Mon Jun 9 01:33:17 CEST 2014
On 08/06/14 19:56, Mario Py wrote:
> Hi everyone, this is very basic/beginner question.
Please don;t reply to an existing message to start a new discussion. It
messes up the threading and makes it harder for people searching the
archives in the future.
> I'm reading TXT file, two words per line that are separated by TAB:
> question, rightAnswer = line.strip().split('\t')
> I would like to use TXT file that it would be separated by coma.
> How do I change that line of code?
You should probably use the csv module instead, it is designed for
reading comma separated files (or tab or any other character).
But if you really do only have two fields and you know they won't have
commas within them then you can do it with split()...
> I tried these two versions but it is not working:
> question, rightAnswer = line.strip().split('\c') # c for coma?
> question, rightAnswer = line.strip().split('\,') # , for coma?
Since comma is not a special character you don't need the escape(\)
character. So your line should just be:
question, rightAnswer = line.strip().split(',')
Author of the Learn to Program web site
More information about the Tutor