Skip to content

Cases#

In fact, snake, kebab, etc. are not functions. They are instances of the Case class which has implemented the object.__call__ dunder method for convenience: Case.__call__. This declarative syntax allows flexibly describe text cases while maintaining all functionality.

You can see a complete list of all built-in cases in the API Reference.

How the case conversion works?

The case conversion happens in three steps:

  1. Splitting: the input text is divided into words by scanning for boundaries. Boundaries are conditions (or delimiters) that signal where one word ends and another begins. For instance, a boundary might detect an underscore, a change from lowercase to uppercase, or even a digit-to-letter transition. Each time a boundary is detected, the string is split at that position.
  2. Transforming: once the text is split into words, the transform is applied. This function (which you can customize) determines how each word will be transformed. For instance, lowercase conversion, capitalization, or an entirely custom transformation can be applied to each word.
  3. Joining: finally, the transformed words are joined back together using a defined delimiter. This delimiter is specific to the case style (for example, underscores ("_") for snake case or hyphens ("-") for kebab case).

The result is the input text converted into the desired case.

Creating Custom Cases#

Simular to Boundary, there is the Case class that allows you to define a custom case that behaves like a built-in one:

cases/custom_case.py
1
2
3
4
5
6
7
8
from textcase import Case

dot = Case(delimiter=".", transform=lambda words: map(str.lower, words))

dot("Dot case var")  # dot.case.var (1)

dot.match("dot.case.var")  # True (2)
dot.match("Dot case var")  # False (3)
  1. 😄 Since dot is an instance of Case, it already converts text to the dot case—just call it like a function! 🎉
  2. 😄 With dot, you don't need to write a custom function to test for the case; just use its match method! 🎉
  3. 😄 Again, leveraging dot's match method, you can easily verify if a string is in the dot case without any extra code! 🎉

To learn more about building a custom case from scratch, take a look at the Case class.