我有以下代码作为css预处理器的一部分,我正在工作。本节接受用户定义的变量并将它们插入到代码中。正则表达式只有在被空格、大括号、方括号、逗号、引号或运算符包围时才替换。当我运行它时,我只会每隔一段时间替换一次变量。你知道吗
def insert_vars(ccss, variables):
for var in variables.keys():
replacer = re.compile(r"""(?P<before>[,+\[(\b{:"'])\$""" + var + """(?P<after>[\b}:"'\])+,])""")
ccss = replacer.sub(r"\g<before>" + variables[var] + r"\g<after>", ccss)
del replacer
re.purge()
return ccss.replace(r"\$", "$")
当我和你一起跑的时候
insert_vars("hello $animal, $nounification != {$noun}ification.", {"animal": "python", "noun": "car"})
有50%的时间它会回来
hello $animal, $nounification != {car}ification.
其他50%
hello $animal, $nounification != {$noun}ification.
有人知道为什么吗?你知道吗
实际情况是,您的
return
关键字是循环的一部分,如acjr stated in the comments。你知道吗这意味着循环只能运行一次迭代。你知道吗
.keys()
的顺序未定义,'animal'
或'noun'
可以排在第一位。你知道吗有一半的时间,你的代码会先得到
'noun'
,这是正确的,或者先得到'animal'
,这是没有效果的。你知道吗因此,应该将
return
的缩进减少到循环之外。你知道吗相关问题 更多 >
编程相关推荐