我试图剥离一行代码,以便只保存结尾的注释。因为#
符号可以包含在""
标记中,为此,我尝试遍历"
标记的行捕捉对,以便忽略""
标记中的任何#
标记。当我在下面的代码中使用代码可视化器时,在第二个for循环之后,它似乎开始处理s
,就好像它刚刚去掉了第一个"
标记一样。我看不出我做错了什么,因为我在第19行包含的print语句显示s
已经被剥离到第二个"
之后,但是当代码返回到顶部时,它会从第一个"
之后再次开始循环。你知道我做错了什么吗?你知道吗
s = '("8# " + str" #9 " + line) #lots of hash(#) symbols here'
quoteCount = 0
for char in s:
if quoteCount%2 == 0:
if char == '#':
s = s[s.index('#'):]
break
if char == '"':
quoteCount = quoteCount + 1
s = s[s.index('"'):]
s = s.lstrip('"')
for char in s:
if char == '"':
quoteCount = quoteCount + 1
s = s[s.index('"'):]
s = s.lstrip('"')
print(s)
break
print(s)
如果我正确理解你的问题,你只想保留最后的评论(这里有很多散列符号)。 为此,不需要嵌套for循环。你知道吗
使用正则表达式更容易删除带引号的字符串:
输出:
您的代码过于复杂,因此我建议您使用另一种方法来查找注释,如前面提到的regex或我提出的注释。你知道吗
相关问题 更多 >
编程相关推荐