liveBook · Manning

Character class

As explained in Python How-To

A character class is a regular-expression shorthand or bracketed construct that matches characters sharing a specified property or membership condition.

A character class matches characters selected by a property or membership condition. Use shorthand classes such as \d for digits, \s for whitespace, and \w for word characters, or define a set with brackets such as [lmn]. section 2.4.3

Build bracketed classes from individual characters, ranges, or complements:

  • [abcxyz] matches any listed character, while [a-z] and [A-Z] match lowercase and uppercase ranges. section 2.4.3
  • Combine ranges, as in [a-dw-z], to match characters from either range. section 2.4.3
  • Use complementary shorthand classes such as \D, \S, and \W for nondigits, nonwhitespace, and nonword characters; use [^a] for any character except a. section 2.4.3

Inspecting character classes

For test_text = "#1$2m_ M\t", re.findall("\\d", test_text) returns ['1', '2'], while re.findall("[lmn]", test_text) returns ['m']. The bracketed class selects only characters in its set. section 2.4.3

\d       any decimal digit
\D       any character that is not a decimal digit
\s       any whitespace, including space, \t, \n, \r, \f, \v
\S       any character that isn't a whitespace
\w       any word character, means alphanumeric plus underscores
\W       any character that is not a word character
.        any character except a newline
[]       a set of defined characters

Compare the common shorthand classes, the dot wildcard, and bracket notation in one quick reference. section 2.4.3

How Python How-To covers it

How deep it goes
Explains shorthand, ranges, combinations, complements, and bracket syntax with matching output, while deferring broader pattern operators.
Examples
Uses [lmn], [a-z], [^a], \d, \D, \s, \S, \w, and \W against short test strings.
What it assumes
Assumes basic regular-expression pattern use and raw-string notation, then teaches character-set choices through concrete examples.
What you can do after
Apply it via regular-expression search and find-all functions to locate selected characters in strings.
How it connects
Connects character classes with regular expressions, quantifiers, boundary anchors, groups, and named groups.

Also explained in

Compare how 9 books explain character class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.