str.startswith() not working as I intended

前端 未结 5 1202
滥情空心
滥情空心 2021-01-29 11:13

I can\'t see why this won\'t work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with \"\"\". For some reason, it gets caug

5条回答
  •  太阳男子
    2021-01-29 11:41

    As long as lines start or end with a comment, the code below should work.

    However, keep in mind that the docstrings can start or end in the middle of a line of code.

    Also, you'll need to code for triple single-quotes as well as docstrings assigned to variables which aren't really comments.

    Does this get you closer to an answer?

    def count_loc(infile):
      skipping_comments = False
      loc = 0 
      for line in infile:
        # Skip one-liners
        if line.strip().startswith("#"): continue
        # Toggle multi-line comment finder: on and off
        if line.strip().startswith('"""'):
          skipping_comments = not skipping_comments
        if line.strip().endswith('"""'):
          skipping_comments = not skipping_comments
          continue
        if skipping_comments: continue
        print line,
    

提交回复
热议问题