Skip to content
ExamSpine

Lesson 5.2 · Write it

First N characters

A functionPython or Java7 tests, 4 of them hidden

On a phone? Put the lines in order instead

Write a function that returns the first n characters of a text value.

  1. text has at least one character. It contains only English letters, digits, spaces and punctuation.
  2. n is at least 1, and at most the number of characters in text.

Only the value your function returns is checked.

def first_n_chars(text: str, n: int) -> str

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • first_n_chars("hello", 3) should return "hel": the first 3 of 5 characters (rule 2)
  • first_n_chars("abcdef", 1) should return "a": n is 1, the smallest it can be (rule 2)
  • first_n_chars("xyz", 3) should return "xyz": n is the whole length, so the whole text comes back (rule 2)

public static String firstNChars(String text, int n)

Checking whether Java answers can run here.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • firstNChars("hello", 3) should return "hel": the first 3 of 5 characters (rule 2)
  • firstNChars("abcdef", 1) should return "a": n is 1, the smallest it can be (rule 2)
  • firstNChars("xyz", 3) should return "xyz": n is the whole length, so the whole text comes back (rule 2)
solution.pySolution.java