Editor

Line Number Formatter

Advanced · Write the code · from Python File Handling: Read, Write, and Process Files

From the lesson: Python File Handling: Read, Write, and Process Files

Imagine you have a notebook where you write down important things. You open it, read what's inside, add new notes, and then close it. Python works with files the same way.

Read the lesson

Write a function called add_line_numbers(text) that takes a multi-line string and returns a new string where each line is prefixed with its line number and a colon.

For example, given 'apple\nbanana\ncherry', the function should return '1: apple\n2: banana\n3: cherry'.

After defining the function, call it with the test string and print the result using print(result, end='') to avoid trailing newlines.

def add_line_numbers(text):
# Your code here
pass
result = add_line_numbers('apple\nbanana\ncherry')
print(result, end='')

More File Handling exercises

All Python exercises · 50 practice problems · File I/O & Data Formats quiz