【发布时间】:2018-07-30 12:00:45
【问题描述】:
我正在编写一个正则表达式来查找这样的代码:
if condition:True:
statements
第一个冒号不是==。
到目前为止,我已经想出了这个:r"(if|elif) .* : .* :\n\t"
但是我想找到一种方法来选择第一个:并将其替换为==。问题是,我找不到使用正则表达式替换: 的方法,而不会无意中:用== 替换整个if condition 等,方法是写一个
re.sub(r"(if|elif) .* : .* :\n\t","==",text)
或 b:将脚本中的每个冒号替换为 ==,这将导致类似的错误
NameError: Expected a ':', received '=='
那么,有没有办法只用== 替换一部分正则表达式,还是有另一种我忽略的方法?
应该发生什么
输入:
if 3+4:7:
print("Three plus four is actually seven")
elif 3+6:10:
print("3+4 is not 7, yet 3+6=10")
控制台:Three plus four is actually seven
顺便说一下,这是 Python 3。
【问题讨论】: