要替换#to的多个事件吗//

2024-04-26 14:44:23 发布

您现在位置:Python中文网/ 问答频道 /正文

函数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)"

Tags: ofthe标记renumberreturnlinecode
3条回答
import re
def transform_comments(line_of_code):
    result = re.sub(r"#{1,}",r"//", line_of_code)
    return result

使用*正则表达式运算符

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

从re library文档

* Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match a, ab, or a followed by any number of bs.

我们可以使用+来表示#的一个或多个出现

result = re.sub(r"#+",r"//",line_of_code)

相关问题 更多 >