我正在尝试在python中实现一个函数,该函数检查解析行内的'#'符号是否为字符串变量的一部分。
def comment_part_of_string(line,comment_idx):
"""
:param line: stripped line that has '#' symbol
comment_idx: index of '#' symbol in line
:return: return True when the '#' symbol is inside a string variable
"""
例如,我希望函数为以下内容返回True:
> line="peace'and#much'love"
> comment_idx=line.find('#')
False代表:
> line="peace#love"
> comment_idx=line.find('#')
如何检查分析行中的char是否为字符串变量的一部分?
编辑我尝试了这个,它也起作用:
def comment_part_of_string(line, comment_idx):
"""
:param comment_idx: index of '#' symbol in line
:param line: stripped line that has '#' symbol
:return: return True when the '#' symbol is inside a string variable
"""
if ((line[:comment_idx].count(b"\'") % 2 == 1 and line[comment_idx:].count(b"\'") % 2 == 1)
or (line[:comment_idx].count(b"\"") % 2 == 1 and line[comment_idx:].count(b"\"") % 2 == 1)):
return True
return False
您可以通过检查符号'
前的单引号()的数量来实现#
。如果是偶数,则表示它在字符串文字之外,如果是奇数,则表示在字符串内部。这样做:
def comment_part_of_string(line, comment_idx):
"""
:param line: stripped line that has '#' symbol
comment_idx: index of '#' symbol in line
:return: return True when the '#' symbol is inside a string variable
"""
count = line.split(line[comment_idx])[0].count("'")
if(count % 2):
return True
else:
return False
希望这可以帮助 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句