Vinod
Vinod

Reputation: 1290

Want to replace multiple occurances of # to //

The transform_comments function converts comments in a Python script into those usable by a C compiler. This means looking for text that begins with a hash mark (#) and replacing it with double slashes (//), which is the C single-line comment indicator. For the purpose of this exercise, we'll ignore the possibility of a hash mark embedded inside of a Python command, and assume that it's only used to indicate a comment. We also want to treat repetitive hash marks (##), (###), etc., as a single comment indicator, to be replaced with just (//) and not (#//) or (//#). Fill in the parameters of the substitution method to complete this function.

This is my try:

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

Upvotes: 1

Views: 5147

Answers (5)

Aastha Sharma
Aastha Sharma

Reputation: 41

Below code is working:

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

Upvotes: 1

girlcode
girlcode

Reputation: 21

We could use the + to indicate one or more occurrences of #

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

Upvotes: 2

waithira
waithira

Reputation: 340

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

Upvotes: 0

H H
H H

Reputation: 101

Use the * regex operator

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

from the re library docs

* 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.

Upvotes: 4

prashant_b_h
prashant_b_h

Reputation: 11

import re
def transform_comments(line_of_code):
    result = re.sub(r"#{1,}",r"//", line_of_code)
    return result

Upvotes: 1

Related Questions