Skip to the content

Character classes

Python · Unit 18: Regular expressions

There are shortcuts for families of characters: \d is a digit, \w a letter, digit or underscore, and \s a space.

The pattern is written with an r in front, r"\d", so Python leaves the backslash alone.

import re

t = "room 7 open"
m = re.search(r"\d", t)
print(m.group())

Prints

7

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

    Complete it so that it prints the 4 of the price.

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    What is the difference between \d+ and \d*?

  5. 5. Predict the output

    What does this code print?

  6. 6. Complete the code

    is_pin should accept only four-digit codes. Complete it.

  7. 7. Predict the output

    What does this code print?

  8. 8. Find the bug

    This program should print the complete order number. Which line has the error?

  9. 9. Find the case that fails

    first_num(t) should give back the first number in the text, or 0 if the text has no number at all. Which call breaks it?

  10. 10. Multiple choice

    A code is written with two lowercase letters, a dash and two digits, like ab-99. Which pattern validates it with fullmatch?

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 →