Utility functions

Utility functions for pluralio.

This module provides helper functions that complement the core pluralization/singularization API:

  • join(): Join words into a natural-language list.

  • ordinal(): Convert a number to its ordinal string (1"1st").

  • template(): Interpolate pluralize/singularize into string templates.

pluralio.utils.join(words: Iterable[str], *, conjunction: str = 'and', final_sep: str = ', ', sep: str = ', ') str[source]

Join words into a natural-language list.

Parameters:
  • words – Iterable of strings to join.

  • conjunction – Conjunction word for the last item. Defaults to "and".

  • final_sep – Separator before the conjunction. Defaults to ", ". Pass "" for no comma before the conjunction (Oxford comma removal).

  • sep – Separator between items (except before the conjunction). Defaults to ", ".

Returns:

A natural-language string joining all words.

Example

>>> join(["apple"])
'apple'
>>> join(["apple", "banana"])
'apple and banana'
>>> join(["apple", "banana", "carrot"])
'apple, banana, and carrot'
>>> join(["apple", "banana", "carrot"], final_sep="")
'apple, banana and carrot'
>>> join(["apple", "banana", "carrot"], conjunction="or")
'apple, banana, or carrot'
pluralio.utils.ordinal(number: int | str) str[source]

Convert a number to its ordinal string representation.

Parameters:

number – An integer or a string representation of an integer.

Returns:

The ordinal string (e.g. "1st", "2nd", "3rd", "11th").

Raises:

ValueError – If number cannot be converted to an integer.

Example

>>> ordinal(1)
'1st'
>>> ordinal(2)
'2nd'
>>> ordinal(3)
'3rd'
>>> ordinal(11)
'11th'
>>> ordinal(21)
'21st'
>>> ordinal("101")
'101st'
>>> ordinal(0)
'0th'
pluralio.utils.template(text: str, **kwargs: object) str[source]

Interpolate pluralize/singularize into a string template.

Placeholders use the syntax {name}, {name:pluralize}, or {name:singularize}. When :pluralize is used, the function looks for a count key in kwargs (or a custom count variable specified as {name:pluralize:count_var}) to enable count-aware pluralization.

Parameters:
  • text – Template string with placeholders.

  • **kwargs – Values for placeholder substitution. If a count key is present, it is used for count-aware pluralization. A custom count variable can be specified in the placeholder syntax (e.g. {word:pluralize:n} uses kwargs["n"] as the count).

Returns:

The interpolated string.

Raises:

KeyError – If a placeholder name is not found in kwargs.

Example

>>> template("I have {count} {word:pluralize}", count=5, word="cat")
'I have 5 cats'
>>> template("I have {count} {word:pluralize}", count=1, word="cat")
'I have 1 cat'
>>> template("The {word:singularize} is here", word="mice")
'The mouse is here'
>>> template("{n} {word:pluralize} arrived", n=3, word="box")
'3 boxes arrived'