想要使用python regex模块/类的“ sub”方法将//多次出现替换为//

问题描述

transform_comments函数将Python脚本中的注释转换为C编译器可用的注释。这意味着查找以井号(#)开头的文本,并用双斜杠(//)代替它,这是C单行注释指示符。出于本练习的目的,我们将忽略在Python命令中嵌入井号的可能性,并假定该井号仅用于指示注释。我们还希望将重复的哈希标记(##),(###)等作为单个注释指示符,而仅替换为(//)而不是(#//)或(//#) 。填写替换方法的参数以完成此功能:

这是我的尝试:

import re
def transform_comments(line_of_code):
  result = re.sub(r'###',r'//',line_of_code)
  return result

print(transform_comments("### Start of program")) 
# Should be "// Start of program"
print(transform_comments("  number = 0   ## Initialize the variable")) 
# Should be "  number = 0   // Initialize the variable"
print(transform_comments("  number += 1   # Increment the variable")) 
# Should be "  number += 1   // Increment the variable"
print(transform_comments("  return(number)")) 
# Should be "  return(number)"

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)