878196. Learn to Comment - Python

Basic

Learn to Comment - Python

Summary

The problem "Learn to Comment" is a basic programming task that focuses on commenting code in Python. The goal is to write Python code that prints out comments from a given string.

Detailed Explanation

The approach to this problem is straightforward: iterate through the input string and identify comment lines (i.e., lines starting with #). For each comment line, extract the text after the # symbol and print it out. Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the extracted comments.
  2. Iterate through each line in the input string using a loop (e.g., for line in input_string.split('\n'):).
  3. Check if the current line is a comment by checking if it starts with #. If it does, proceed to step 4. Otherwise, skip to the next iteration.
  4. Extract the text after the # symbol using string manipulation (e.g., comment = line.split('#')[1].strip()). This will give us the actual comment text.
  5. Append the extracted comment text to the result string.

Time complexity: O(n), where n is the length of the input string, since we're iterating through each line once. Space complexity: O(1), as we only need a constant amount of space to store the result and temporary variables.

Optimized Solutions

Python

View on GeeksforGeeks
public class LearnToComment {
  public static String learnToComment(String inputString) {
    StringBuilder result = new StringBuilder();
    for (String line : inputString.split("\n")) {
      if (line.startsWith("#")) {
        int commentStart = line.indexOf('#') + 1;
        result.append(line.substring(commentStart).trim()).append('\n');
      }
    }
    return result.toString().trim();
  }

  public static void main(String[] args) {
    String inputString = "Hello #world, this is a test #comments!";
    System.out.println(learnToComment(inputString));
  }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.