I'm trying to read data from a text file into Python. The file consists of lines like this:
SAMPLE_0001 2000 57 1 103 51 0 NA
For ease of data management, I'd like to save that line as a list:
[SAMPLE_0001,2000,57,1,103,51,0,NA]
I wrote the following function to do that:
def line_breaker(line):
words=[]
if line[0]==' ':
in_word=False
else:
in_word=True
word=[]
for i in range(len(line)):
if in_word==True and line[i]!=' ':
word.append(line[i])
elif in_word==True and line[i]==' ':
in_word=False
words.append(word)
word=[]
elif in_word==False and line[i]!=' ':
in_word=True
word.append(line[i])
if i==len(line)-1 and line[i]!=' ':
word.append(line[i])
words.append(word)
return words
Unfortunately, this doesn't work as intended. When I apply it to the example above, I get the whole line as one long string. On closer inspection, this was because the condition line[i]==' '
failed to trigger on the blank spaces. I guess I should replace ' '
with something else.
When I ask Python to print the 11th position in the example, it displays nothing. That's totally unhelpful. I then asked it to print the type of the 11th position in the example; I got <class 'str'>
.
So what should I use to detect spaces?