gpt4 book ai didi

python - 注释和变量之间的 line.strip

转载 作者:行者123 更新时间:2023-12-01 04:21:14 28 4
gpt4 key购买 nike

我有以下代码行:

if line.lstrip().startswith('#%s' % debug_variable):

这与文件中的以下行很好匹配:

#debug true

我想做的是找到一种匹配以下情况的方法:

# key true
# key true
#<tab>key true

即注释 (#) 和键之间可以有任意大小的空格

所以本质上,我需要一个正则表达式来在 # 和我的 %s 变量之间起作用

我尝试过以下方法:

if line.lstrip().startswith('#\w%s' % debug_variable):

但运气不太好。

最佳答案

如果您愿意使用正则表达式,则不需要 startswith

if re.match(r'#\s*' + debug_variable, line):

if re.match(r'#[ \t]*' + debug_variable, line):

请注意,re.match 尝试从字符串的开头进行匹配,因此不需要行 anchor ^ 的开头。

关于python - 注释和变量之间的 line.strip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671574/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com