Search code examples
pythonlist-comprehensionenumerate

Outputting the line number of a text in a .txt-file, which doesn´t include spaces with list-comprehension


I have a question reagarding my code, if anybody has some clues how to solve it. I need to write only one line of code, which outputs the line numbers of those lines that don´t include spaces between the words. My attempt was the following:

[line for line in range(len(open('test.txt').readlines())) if ' ' not in open('test.txt').readlines(line)]

I tried to use enumerate. But it didn`t work out as I intended. I would appreciate any clue on how to change my code, if anything of my code is correct.


Solution

  • This does it:

    print([i for i,line in (enumerate(open("test.txt").readlines())) if " " not in line])
    

    Content of example file:

    apricot
    a p p l e
    mango
    banana
    che rry
    

    Output:

    [0, 2, 3]