Echo Lines with Numbers

Easy ⏱ 8 min 76% acceptance ★★★★☆ 4.2
Write a function number_lines(text) that takes a multi-line string text (lines separated by \n) and returns a new string where each line is prefixed with its 1-based line number and a period, e.g. "1. first line". Lines are joined back together with \n.

Examples

Example 1
Input
number_lines("apple\nbanana")
Output
'1. apple\n2. banana'
Explanation

Two lines, each numbered.

Example 2
Input
number_lines("solo")
Output
'1. solo'
Explanation

Single line still gets numbered.

Constraints

  • text has at least one line; may or may not end with a newline (ignore trailing empty line if present).

Topics

Input & Outputstring formatting

Companies

IBMOracle

Hints

Hint 1

`text.split("\n")` gives the individual lines.

Hint 2

Use enumerate(lines, start=1) to number them, then "\n".join(...).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.