【问题标题】:Want to replace multiple occurances of # to //想要将多次出现的#替换为//
【发布时间】:2020-10-04 14:26:32
【问题描述】:

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

这是我的尝试:

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

【问题讨论】:

    标签: python regex python-re


    【解决方案1】:

    使用* 正则表达式运算符

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

    来自 re 库文档

    * 使生成的 RE 匹配前一个 RE 的 0 次或多次重复,尽可能多的重复。 ab* 将匹配 aaba,后跟任意数量的 bs。

    【讨论】:

    • @H H 感谢您的帮助,您的解决方案已经奏效,但是我稍后尝试使用此 result = re.sub(r'\#+',r'//', line_of_code),这也有效。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:
      import re
      def transform_comments(line_of_code):
          result = re.sub(r"#{1,}",r"//", line_of_code)
          return result
      

      【讨论】:

        【解决方案4】:

        以下代码正在运行:

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

        【讨论】:

        • 你的回答是对的。只是一个建议:尝试在以后的回复中多解释一点,而不仅仅是一行代码
        【解决方案5】:
        import re
        def transform_comments(line_of_code):
          result = re.sub(r'(#*#) ',r'// ',line_of_code)
          return result
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-16
          • 1970-01-01
          • 2019-04-19
          • 2014-04-13
          • 1970-01-01
          • 1970-01-01
          • 2021-01-08
          • 1970-01-01
          相关资源
          最近更新 更多