Python for loop sepping line as you g

2024-09-28 17:05:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图剥离一行代码,以便只保存结尾的注释。因为#符号可以包含在""标记中,为此,我尝试遍历"标记的行捕捉对,以便忽略""标记中的任何#标记。当我在下面的代码中使用代码可视化器时,在第二个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)

Tags: 代码in标记forindexif可视化结尾
3条回答

如果我正确理解你的问题,你只想保留最后的评论(这里有很多散列符号)。 为此,不需要嵌套for循环。你知道吗

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('"')

print(s)

使用正则表达式更容易删除带引号的字符串:

import re
s = '("8# " + str" #9 " + line) #lots of hash(#) symbols here'
pattern = r'"[^"]*"'
s = re.sub(pattern, '', s)
print s[s.index('#'):]

输出:

#lots of hash(#) symbols here

您的代码过于复杂,因此我建议您使用另一种方法来查找注释,如前面提到的regex或我提出的注释。你知道吗

s = '("8# " + str" #9 " + line) #lots of hash(#) symbols here'
s = s[s.rfind('"') + 1:]  # Get to the last quotation mark

if s.find('#') >= 0:  # The first # sign should start the comment if there is one
    s = s[s.find('#'):]

else:
    s = ''  # No comment was found

print(s)

相关问题 更多 >