Skip to the content

Recursion with text

Python · Unit 11: Recursion

A string splits the same way as a list: t[0] is the first letter and t[1:] is the rest.

The base case is usually the empty string, "".

t = "sun"
print(t[0], t[1:])
print("s"[1:] == "")

Prints

s un
True

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so it repeats each letter twice.

  3. 3. Predict the output

    What does this code print?

  4. 4. Find the bug

    This program should print "pit", the word backwards. Which line has the bug?

  5. 5. Multiple choice

    What does this function do?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank to check the middle of the string.

  8. 8. Find the bug

    This program should print True, because 1221 reads the same backwards. Which line has the bug?

  9. 9. Find the case that fails

    is_pal(t) should say whether t is a palindrome, ignoring capital letters. Which call does it fail on?

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →