Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Formatting a Phone Number | Recursion and Lambda Functions
Python Functions Tutorial

Challenge: Formatting a Phone Number

Recall that a recursive function solves a problem by calling itself with a simpler input, until it reaches the base case that stops the recursion:

1234
def list_sum(numbers): if not numbers: # Base case return 0 return numbers[0] + list_sum(numbers[1:]) # Recursive case

Notice how each recursive call works on a smaller version of the input — in this case, the list without its first element. The same approach applies when processing strings character by character.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 2
single

single

Challenge: Formatting a Phone Number

Swipe to show menu

Recall that a recursive function solves a problem by calling itself with a simpler input, until it reaches the base case that stops the recursion:

1234
def list_sum(numbers): if not numbers: # Base case return 0 return numbers[0] + list_sum(numbers[1:]) # Recursive case

Notice how each recursive call works on a smaller version of the input — in this case, the list without its first element. The same approach applies when processing strings character by character.

Task

Swipe to start coding

Given a string representing a phone number, which may contain spaces, dashes, parentheses, or other non-numeric characters. The goal is to extract only the digits using recursion.

  1. If the input string number is empty, return an empty string;
  2. Check if the first character of the string number is a digit using the isdigit() method;
  3. If it is a digit, concatenate it with the result of a recursive call passing the substring starting from the second character;
  4. If it is not a digit, make a recursive call skipping the first character.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 2
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt