函数transform_comments
将Python脚本中的注释转换为可由C编译器使用的注释。这意味着查找以哈希标记(#
)开头的文本,并将其替换为双斜杠(//
),这是C单行注释指示符。在本练习中,我们将忽略Python命令中嵌入哈希标记的可能性,并假设它仅用于指示注释。我们还希望将重复的散列标记(##
)、(###
)等作为单个注释指示符,用just(//
)代替,而不是(#//
)或(//#
)。填写替换方法的参数以完成此功能
这是我的尝试:
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)"
使用
*
正则表达式运算符从re library文档
我们可以使用
+
来表示#
的一个或多个出现相关问题 更多 >
编程相关推荐