Rach
Rach

Reputation: 13

Execution of endswith function

It seems like if statement doesn't execute or may be because i have made some mistake.

I tried,

ends = line.endswith('/')

if (line.startswith('  ') and ends == True)

But doesn't work. If statement doesn't run

count = 0
for line in f1:
    if (line.startswith('  ') and line.endswith('/')):
        count = count + 1
        continue

    elif line.startswith(('  ', ' ', '//')):
        continue
    else:
        if (count == 0):
            f2.write(line)
            count = 0

If line starts with '//' or single or double spaces, those lines should not be printed (condition 1). Also, if a line starts with double space and ends with '/' and next line doesn't satisfy condition 1, it should no be printed. Lines without condition 1 must be printed

Input:

//abcd

  abcd/

This line should not be printed

This has to be printed

Expected Output:

This has to be printed

Actual output:

This line should not be printed

This has to be printed

Upvotes: 1

Views: 60

Answers (1)

blhsing
blhsing

Reputation: 107015

Lines generated by iterating through a file object always end with a newline character (unless it's the last line of the file and the file does not end with a trailing newline character). You can apply rstrip to the line before you use endswith to test if a line ends with a certain character. Also, you should reset counter (with count = 0) outside of the if (count == 0): block; otherwise the statement would never run:

from io import StringIO
f1 = StringIO('''//abcd
  abcd/
This line should not be printed
This has to be printed
''')
f2 = StringIO()
count = 0
for line in f1:
    if (line.startswith('  ') and line.rstrip().endswith('/')):
        count = count + 1
    elif not line.startswith(('  ', ' ', '//')):
        if (count == 0):
            f2.write(line)
        count = 0
print(f2.getvalue())

This outputs:

This has to be printed

Upvotes: 1

Related Questions