endwith函数的执行

时间:2019-03-25 12:38:44

标签: python python-2.7

似乎if语句未执行,或者可能是因为我犯了一些错误。

我尝试过

ends = line.endswith('/')

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

但是不起作用。如果语句未运行

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

如果行以'//'或单或双空格开头,则不应打印这些行(条件1)。另外,如果一行以双倍空格开头,并以'/'结尾,并且下一行不满足条件1,则不应打印该行。没有条件1的行必须打印

输入:

//abcd

  abcd/

This line should not be printed

This has to be printed

预期输出:

This has to be printed

实际输出:

This line should not be printed

This has to be printed

1 个答案:

答案 0 :(得分:1)

通过遍历文件对象生成的行始终以换行符结尾(除非它是文件的最后一行,并且文件不以尾随换行符结尾)。在使用rstrip测试行是否以某个特定字符结尾之前,可以将endswith应用于行。另外,您应该在counter块之外重置count = 0(用if (count == 0):);否则该语句将永远不会运行:

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 has to be printed