Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 04

Predefined Classes — Digits, Word Characters, and Spaces

Use Python's predefined regex classes for digits, non-digits, word characters, symbols, spaces, and non-spaces in a string.

Intermediate25 min
Predefined character classes hero Module 18 Lesson 4 digit word space

Python already names the sets you would otherwise write in brackets. A lowercase letter means the set. The uppercase letter means everything else.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • \d, \D, \w, \W, \s, and \S
  • How they line up with bracket classes
  • What \w includes beyond letters and digits

The picture

Each backslash class and its opposite

A predefined class still matches one character. The backslash is part of the pattern, so keep the raw string.

Pattern Matches Close bracket form
\d a digit [0-9] on these examples
\D not a digit [^0-9]
\w a word character letters, digits, and _
\W not a word character symbols and spaces
\s a space, tab, or similar whitespace —
\S anything that is not whitespace —

\d is the short way to write a digit class. \D is the negated form.

\w is slightly wider than [A-Za-z0-9]. In Python it also matches the underscore. A hyphen or an exclamation mark is \W, not \w.

\s matches whitespace, not the letter s. \S is every other character, including letters and digits.

These examples use plain English text, so \d lines up with the digits 0 through 9.

Example

python
import re

text = "Avery Lane 18"
print(re.findall(r"\d", text))
print(re.findall(r"\s", text))
print(re.findall(r"\w", text))
print(re.findall(r"\W", "Avery-7!"))

The first line is the digits 1 and 8 separately. The second line is the spaces. The third line is every letter and digit, one by one. On Avery-7!, \W keeps the hyphen and the exclamation mark.

Key takeaways

  • \d is a digit; \D is not

  • \w is a letter, digit, or underscore; \W is not

  • \s is whitespace; \S is not

  • Each of these still matches one character

  • Next: Quantifiers — one, many, or a chosen count

  • Previous: Character Classes

Loading playground…

Check your understanding

Predefined classes quiz

\d matches:

1 / 10