Python str.startswith()未按预期工作
我不明白这为什么行不通。我正在对传递给函数的字符串执行lstrip,并尝试查看它是否以开头。由于某种原因,它陷入了一个无限循环Python str.startswith()未按预期工作,python,string,python-3.x,Python,String,Python 3.x,我不明白这为什么行不通。我正在对传递给函数的字符串执行lstrip,并尝试查看它是否以开头。由于某种原因,它陷入了一个无限循环 def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not line_t.startswith('#'): print (line, end = '') return line el
def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
以及我的输出:
Enter the file name: test.txt
import re
def count_loc(infile):
以下是我正在阅读的文件的顶部,以供参考:
import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
无论字符串行表示什么,此表达式的计算结果都为True。你想要“和”而不是“或”?你的问题我不清楚
if not line_t.startswith('"""') or not line_t.startswith('#'):
这个if总是令人满意的——要么行不是以开头,要么它不是以开头,要么两者都是。您可能打算使用以及在何处使用or。而True是一个无限循环。完成后需要中断。您还没有提供并退出递归循环的路径。return语句应该可以做到这一点
(...)
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
return find_comment(infile, line)
else:
line = infile.readline()
只要行以注释开头或结尾,下面的代码就可以工作
但是请记住,DROBUG可以在代码行的中间开始或结束。
此外,您还需要编写三重单引号以及分配给非注释变量的docstring代码 这能让你更接近答案吗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,
复制并重新发布:woops,是的,我改变了,但在上面发布的while语句中,它陷入了无限循环。我更新了我原来的帖子来反映这一点是的,没错,但是我现在陷入了无限的while循环。但我不知道为什么,从消息来源得到的任何见解?我更新了我原来的帖子来反映这一点,可能是因为你的while循环说while为True,而你没有中断。只是胡乱猜测……啊,我忘了三个单引号了。这个项目实际上是针对我的C++类,但是我一直在尝试同时教自己Python,并决定了两次。谢谢你的代码,我所需要的只是while循环中的返回语句。出于某种原因,我认为再次调用该函数将打破循环。谢谢!
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,