Skip to content

text (29)

apnumber

apnumber(value: 'float | str') -> str

Converts an integer to Associated Press style.

Required packages: humanize

Example

Jinja call:

{{ 7 | apnumber }}
Result: seven

DocStrings

Examples:

>>> apnumber(0)
'zero'
>>> apnumber(5)
'five'
>>> apnumber(10)
'10'
>>> apnumber("7")
'seven'
>>> apnumber("foo")
'foo'
>>> apnumber(None)
'None'

Parameters:

Name Type Description Default
value (int, float, str)

Integer to convert.

required

Returns:

Name Type Description
str str

For numbers 0-9, the number spelled out. Otherwise, the number. This always returns a string unless the value was not int-able, then str(value) is returned.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def apnumber(value: NumberOrString) -> str:
    """Converts an integer to Associated Press style.

    Examples:
      ```pycon
      >>> apnumber(0)
      'zero'
      >>> apnumber(5)
      'five'
      >>> apnumber(10)
      '10'
      >>> apnumber("7")
      'seven'
      >>> apnumber("foo")
      'foo'
      >>> apnumber(None)
      'None'

      ```

    Args:
        value (int, float, str): Integer to convert.

    Returns:
        str: For numbers 0-9, the number spelled out. Otherwise, the number. This always
            returns a string unless the value was not `int`-able, then `str(value)`
            is returned.
    """
    try:
        if not math.isfinite(float(value)):
            return _format_not_finite(float(value))
        value = int(value)
    except (TypeError, ValueError):
        return str(value)
    if not 0 <= value < 10:
        return str(value)
    return (
        _("zero"),
        _("one"),
        _("two"),
        _("three"),
        _("four"),
        _("five"),
        _("six"),
        _("seven"),
        _("eight"),
        _("nine"),
    )[value]

capitalize

capitalize(s: str) -> str

Capitalize a value. The first character will be uppercase, all others

Example

Jinja call:

{{ "abc" | capitalize }}
Result: Abc

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
320
321
322
323
324
def do_capitalize(s: str) -> str:
    """Capitalize a value. The first character will be uppercase, all others
    lowercase.
    """
    return soft_str(s).capitalize()

center

center(value: str, width: int = 80) -> str

Centers the value in a field of a given width.

Example

Jinja call:

{{ "sth" | center(20) }}
Result: sth

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
634
635
636
def do_center(value: str, width: int = 80) -> str:
    """Centers the value in a field of a given width."""
    return soft_str(value).center(width)

clamp

clamp(value: float, format: str = '{:}', floor: float | None = None, ceil: float | None = None, floor_token: str = '<', ceil_token: str = '>') -> str

Returns number with the specified format, clamped between floor and ceil.

Required packages: humanize

Example

Jinja call:

{{ 0.0001 | clamp(floor=0.01) }}
Result: <0.01

DocStrings

Examples:

>>> clamp(123.456)
'123.456'
>>> clamp(0.0001, floor=0.01)
'<0.01'
>>> clamp(0.99, format="{:.0%}", ceil=0.99)
'99%'
>>> clamp(0.999, format="{:.0%}", ceil=0.99)
'>99%'
>>> clamp(1, format=intword, floor=1e6, floor_token="under ")
'under 1.0 million'
>>> clamp(None) is None
True

Parameters:

Name Type Description Default
value (int, float)

Input number.

required
format str OR callable

Can either be a formatting string, or a callable function that receives value and returns a string.

'{:}'
floor (int, float)

Smallest value before clamping.

None
ceil (int, float)

Largest value before clamping.

None
floor_token str

If value is smaller than floor, token will be prepended to output.

'<'
ceil_token str

If value is larger than ceil, token will be prepended to output.

'>'

Returns:

Name Type Description
str str

Formatted number. The output is clamped between the indicated floor and ceil. If the number is larger than ceil or smaller than floor, the output will be prepended with a token indicating as such.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def clamp(
    value: float,
    format: str = "{:}",
    floor: float | None = None,
    ceil: float | None = None,
    floor_token: str = "<",
    ceil_token: str = ">",
) -> str:
    """Returns number with the specified format, clamped between floor and ceil.

    If the number is larger than ceil or smaller than floor, then the respective limit
    will be returned, formatted and prepended with a token specifying as such.

    Examples:
        ```pycon
        >>> clamp(123.456)
        '123.456'
        >>> clamp(0.0001, floor=0.01)
        '<0.01'
        >>> clamp(0.99, format="{:.0%}", ceil=0.99)
        '99%'
        >>> clamp(0.999, format="{:.0%}", ceil=0.99)
        '>99%'
        >>> clamp(1, format=intword, floor=1e6, floor_token="under ")
        'under 1.0 million'
        >>> clamp(None) is None
        True

        ```

    Args:
        value (int, float): Input number.
        format (str OR callable): Can either be a formatting string, or a callable
            function that receives value and returns a string.
        floor (int, float): Smallest value before clamping.
        ceil (int, float): Largest value before clamping.
        floor_token (str): If value is smaller than floor, token will be prepended
            to output.
        ceil_token (str): If value is larger than ceil, token will be prepended
            to output.

    Returns:
        str: Formatted number. The output is clamped between the indicated floor and
            ceil. If the number is larger than ceil or smaller than floor, the output
            will be prepended with a token indicating as such.

    """
    if value is None:
        return None

    if not math.isfinite(value):
        return _format_not_finite(value)

    if floor is not None and value < floor:
        value = floor
        token = floor_token
    elif ceil is not None and value > ceil:
        value = ceil
        token = ceil_token
    else:
        token = ""

    if isinstance(format, str):
        return token + format.format(value)

    if callable(format):
        return token + format(value)

    msg = (
        "Invalid format. Must be either a valid formatting string, or a function "
        "that accepts value and returns a string."
    )
    raise ValueError(msg)

escape

escape(text: str) -> str

Escape text using Markupsafe library.

Aliases: e

Example

Jinja call:

{{ "<[]>" | escape }}
Result: &lt;[]&gt;

Example

Jinja call:

{{ '"double" quotes' | escape }}
Result: &#34;double&#34; quotes

DocStrings

Parameters:

Name Type Description Default
text str

text to escape

required
Source code in src/jinjarope/textfilters.py
213
214
215
216
217
218
219
220
221
def escape(text: str) -> str:
    """Escape text using Markupsafe library.

    Args:
        text: text to escape
    """
    import markupsafe

    return markupsafe.escape(text)

forceescape

forceescape(value: 't.Union[str, HasHTML]') -> markupsafe.Markup

Enforce HTML escaping. This will probably double escape variables.

Example

Jinja call:

{{ "<>" | forceescape }}
Result: &lt;&gt;

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
138
139
140
141
142
143
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
    """Enforce HTML escaping.  This will probably double escape variables."""
    if hasattr(value, "__html__"):
        value = t.cast("HasHTML", value).__html__()

    return escape(str(value))

fractional

fractional(value: 'float | str') -> str

Convert to fractional number.

Required packages: humanize

Example

Jinja call:

{{ 1.3 | fractional }}
Result: 1 3/10

DocStrings

Examples:

>>> fractional(0.3)
'3/10'
>>> fractional(1.3)
'1 3/10'
>>> fractional(float(1/3))
'1/3'
>>> fractional(1)
'1'
>>> fractional("ten")
'ten'
>>> fractional(None)
'None'

Parameters:

Name Type Description Default
value (int, float, str)

Integer to convert.

required

Returns:

Name Type Description
str str

Fractional number as a string.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def fractional(value: NumberOrString) -> str:
    """Convert to fractional number.

    There will be some cases where one might not want to show ugly decimal places for
    floats and decimals.

    This function returns a human-readable fractional number in form of fractions and
    mixed fractions.

    Pass in a string, or a number or a float, and this function returns:

    * a string representation of a fraction
    * or a whole number
    * or a mixed fraction
    * or the str output of the value, if it could not be converted

    Examples:
        ```pycon
        >>> fractional(0.3)
        '3/10'
        >>> fractional(1.3)
        '1 3/10'
        >>> fractional(float(1/3))
        '1/3'
        >>> fractional(1)
        '1'
        >>> fractional("ten")
        'ten'
        >>> fractional(None)
        'None'

        ```

    Args:
        value (int, float, str): Integer to convert.

    Returns:
        str: Fractional number as a string.
    """
    try:
        number = float(value)
        if not math.isfinite(number):
            return _format_not_finite(number)
    except (TypeError, ValueError):
        return str(value)
    from fractions import Fraction

    whole_number = int(number)
    frac = Fraction(number - whole_number).limit_denominator(1000)
    numerator = frac.numerator
    denominator = frac.denominator
    if whole_number and not numerator and denominator == 1:
        # this means that an integer was passed in
        # (or variants of that integer like 1.0000)
        return f"{whole_number:.0f}"

    if not whole_number:
        return f"{numerator:.0f}/{denominator:.0f}"

    return f"{whole_number:.0f} {numerator:.0f}/{denominator:.0f}"

indent

indent(s: str, width: Union[int, str] = 4, first: bool = False, blank: bool = False) -> str

Return a copy of the string with each line indented by 4 spaces. The

Example

Jinja call:

{{ "abc
def" | indent }}
Result: abc def

Example

Jinja call:

{{ "first
second" | indent(width=4, first=true) }}
Result: first second

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def do_indent(
    s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
) -> str:
    """Return a copy of the string with each line indented by 4 spaces. The
    first line and blank lines are not indented by default.

    :param width: Number of spaces, or a string, to indent by.
    :param first: Don't skip indenting the first line.
    :param blank: Don't skip indenting empty lines.

    .. versionchanged:: 3.0
        ``width`` can be a string.

    .. versionchanged:: 2.10
        Blank lines are not indented by default.

        Rename the ``indentfirst`` argument to ``first``.
    """
    if isinstance(width, str):
        indention = width
    else:
        indention = " " * width

    newline = "\n"

    if isinstance(s, Markup):
        indention = Markup(indention)
        newline = Markup(newline)

    s += newline  # this quirk is necessary for splitlines method

    if blank:
        rv = (newline + indention).join(s.splitlines())
    else:
        lines = s.splitlines()
        rv = lines.pop(0)

        if lines:
            rv += newline + newline.join(
                indention + line if line else line for line in lines
            )

    if first:
        rv = indention + rv

    return rv

intcomma

intcomma(value: 'float | str', ndigits: int | None = None) -> str

Converts an integer to a string containing commas every three digits.

Required packages: humanize

Example

Jinja call:

{{ 10000000 | intcomma }}
Result: 10,000,000

DocStrings

Examples:

>>> intcomma(100)
'100'
>>> intcomma("1000")
'1,000'
>>> intcomma(1_000_000)
'1,000,000'
>>> intcomma(1_234_567.25)
'1,234,567.25'
>>> intcomma(1234.5454545, 2)
'1,234.55'
>>> intcomma(14308.40, 1)
'14,308.4'
>>> intcomma("14308.40", 1)
'14,308.4'
>>> intcomma(None)
'None'

Parameters:

Name Type Description Default
value (int, float, str)

Integer or float to convert.

required
ndigits (int, None)

Digits of precision for rounding after the decimal point.

None

Returns:

Name Type Description
str str

String containing commas every three digits.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
    """Converts an integer to a string containing commas every three digits.

    For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some
    compatibility with Django's `intcomma`, this function also accepts floats.

    Examples:
        ```pycon
        >>> intcomma(100)
        '100'
        >>> intcomma("1000")
        '1,000'
        >>> intcomma(1_000_000)
        '1,000,000'
        >>> intcomma(1_234_567.25)
        '1,234,567.25'
        >>> intcomma(1234.5454545, 2)
        '1,234.55'
        >>> intcomma(14308.40, 1)
        '14,308.4'
        >>> intcomma("14308.40", 1)
        '14,308.4'
        >>> intcomma(None)
        'None'

        ```

    Args:
        value (int, float, str): Integer or float to convert.
        ndigits (int, None): Digits of precision for rounding after the decimal point.

    Returns:
        str: String containing commas every three digits.
    """
    thousands_sep = thousands_separator()
    decimal_sep = decimal_separator()
    try:
        if isinstance(value, str):
            value = value.replace(thousands_sep, "").replace(decimal_sep, ".")
            if not math.isfinite(float(value)):
                return _format_not_finite(float(value))
            if "." in value:
                value = float(value)
            else:
                value = int(value)
        else:
            if not math.isfinite(float(value)):
                return _format_not_finite(float(value))
            float(value)
    except (TypeError, ValueError):
        return str(value)

    if ndigits is not None:
        orig = "{0:.{1}f}".format(value, ndigits)
    else:
        orig = str(value)
    orig = orig.replace(".", decimal_sep)
    while True:
        new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{thousands_sep}\g<2>", orig)
        if orig == new:
            return new
        orig = new

intword

intword(value: 'float | str', format: str = '%.1f') -> str

Converts a large integer to a friendly text representation.

Required packages: humanize

Example

Jinja call:

{{ 10000000 | intword }}
Result: 10.0 million

DocStrings

Examples:

>>> intword("100")
'100'
>>> intword("12400")
'12.4 thousand'
>>> intword("1000000")
'1.0 million'
>>> intword(1_200_000_000)
'1.2 billion'
>>> intword(8100000000000000000000000000000000)
'8.1 decillion'
>>> intword(None)
'None'
>>> intword("1234000", "%0.3f")
'1.234 million'

Parameters:

Name Type Description Default
value (int, float, str)

Integer to convert.

required
format str

To change the number of decimal or general format of the number portion.

'%.1f'

Returns:

Name Type Description
str str

Friendly text representation as a string, unless the value passed could not be coaxed into an int.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def intword(value: NumberOrString, format: str = "%.1f") -> str:
    """Converts a large integer to a friendly text representation.

    Works best for numbers over 1 million. For example, 1_000_000 becomes "1.0 million",
    1200000 becomes "1.2 million" and "1_200_000_000" becomes "1.2 billion". Supports up
    to decillion (33 digits) and googol (100 digits).

    Examples:
        ```pycon
        >>> intword("100")
        '100'
        >>> intword("12400")
        '12.4 thousand'
        >>> intword("1000000")
        '1.0 million'
        >>> intword(1_200_000_000)
        '1.2 billion'
        >>> intword(8100000000000000000000000000000000)
        '8.1 decillion'
        >>> intword(None)
        'None'
        >>> intword("1234000", "%0.3f")
        '1.234 million'

        ```

    Args:
        value (int, float, str): Integer to convert.
        format (str): To change the number of decimal or general format of the number
            portion.

    Returns:
        str: Friendly text representation as a string, unless the value passed could not
            be coaxed into an `int`.
    """
    try:
        if not math.isfinite(float(value)):
            return _format_not_finite(float(value))
        value = int(value)
    except (TypeError, ValueError):
        return str(value)

    if value < 0:
        value *= -1
        negative_prefix = "-"
    else:
        negative_prefix = ""

    if value < powers[0]:
        return negative_prefix + str(value)

    for ordinal_, power in enumerate(powers[1:], 1):
        if value < power:
            chopped = value / float(powers[ordinal_ - 1])
            powers_difference = powers[ordinal_] / powers[ordinal_ - 1]
            if float(format % chopped) == powers_difference:
                chopped = value / float(powers[ordinal_])
                singular, plural = human_powers[ordinal_]
                return (
                    negative_prefix
                    + " ".join(
                        [format, _ngettext(singular, plural, math.ceil(chopped))]
                    )
                ) % chopped

            singular, plural = human_powers[ordinal_ - 1]
            return (
                negative_prefix
                + " ".join([format, _ngettext(singular, plural, math.ceil(chopped))])
            ) % chopped

    return negative_prefix + str(value)

lower

lower(s: str) -> str

Convert a value to lowercase.

Example

Jinja call:

{{ "ABC" | lower }}
Result: abc

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
218
219
220
def do_lower(s: str) -> str:
    """Convert a value to lowercase."""
    return soft_str(s).lower()

lower_camel_case

lower_camel_case(text: str) -> str

Convert given text to lower-camel-case.

Example

Jinja call:

{{ "some_text" | lower_camel_case }}
Result: someText

DocStrings

Parameters:

Name Type Description Default
text str

The string to convert

required
Source code in src/jinjarope/textfilters.py
61
62
63
64
65
66
67
68
69
70
71
def lower_camel_case(text: str) -> str:
    """Convert given text to lower-camel-case.

    Args:
        text: The string to convert
    """
    # do nothing if nothing to camel
    if "_" not in text:
        return text
    first, *others = text.split("_")
    return "".join([first.lower(), *map(str.title, others)])

lstrip

lstrip(text: str, chars: str | None = None) -> str

Strip given chars from beginning of string.

Example

Jinja call:

{{ " abc" | lstrip }}
Result: abc

DocStrings

Parameters:

Name Type Description Default
text str

The text to strip the chars from

required
chars str | None

The chars to remove

None
Source code in src/jinjarope/textfilters.py
41
42
43
44
45
46
47
48
def lstrip(text: str, chars: str | None = None) -> str:
    """Strip given chars from beginning of string.

    Args:
        text: The text to strip the chars from
        chars: The chars to remove
    """
    return text.lstrip(chars)

naturalsize

naturalsize(value: float | str, binary: bool = False, gnu: bool = False, format: str = '%.1f') -> str

Format a number of bytes like a human-readable filesize (e.g. 10 kB).

Required packages: humanize

Example

Jinja call:

{{ 22 | naturalsize }}
Result: 22 Bytes

DocStrings

Examples:

>>> naturalsize(3000000)
'3.0 MB'
>>> naturalsize(300, False, True)
'300B'
>>> naturalsize(3000, False, True)
'2.9K'
>>> naturalsize(3000, False, True, "%.3f")
'2.930K'
>>> naturalsize(3000, True)
'2.9 KiB'
>>> naturalsize(10**28)
'10.0 RB'
>>> naturalsize(10**34 * 3)
'30000.0 QB'
>>> naturalsize(-4096, True)
'-4.0 KiB'

Parameters:

Name Type Description Default
value (int, float, str)

Integer to convert.

required
binary bool

If True, uses binary suffixes (KiB, MiB) with base 210 instead of 103.

False
gnu bool

If True, the binary argument is ignored and GNU-style (ls -sh style) prefixes are used (K, M) with the 2**10 definition.

False
format str

Custom formatter.

'%.1f'

Returns:

Name Type Description
str str

Human readable representation of a filesize.

Source code in .venv/lib/python3.12/site-packages/humanize/filesize.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def naturalsize(
    value: float | str,
    binary: bool = False,
    gnu: bool = False,
    format: str = "%.1f",
) -> str:
    """Format a number of bytes like a human-readable filesize (e.g. 10 kB).

    By default, decimal suffixes (kB, MB) are used.

    Non-GNU modes are compatible with jinja2's `filesizeformat` filter.

    Examples:
        ```pycon
        >>> naturalsize(3000000)
        '3.0 MB'
        >>> naturalsize(300, False, True)
        '300B'
        >>> naturalsize(3000, False, True)
        '2.9K'
        >>> naturalsize(3000, False, True, "%.3f")
        '2.930K'
        >>> naturalsize(3000, True)
        '2.9 KiB'
        >>> naturalsize(10**28)
        '10.0 RB'
        >>> naturalsize(10**34 * 3)
        '30000.0 QB'
        >>> naturalsize(-4096, True)
        '-4.0 KiB'

        ```

    Args:
        value (int, float, str): Integer to convert.
        binary (bool): If `True`, uses binary suffixes (KiB, MiB) with base
            2<sup>10</sup> instead of 10<sup>3</sup>.
        gnu (bool): If `True`, the binary argument is ignored and GNU-style
            (`ls -sh` style) prefixes are used (K, M) with the 2**10 definition.
        format (str): Custom formatter.

    Returns:
        str: Human readable representation of a filesize.
    """
    if gnu:
        suffix = suffixes["gnu"]
    elif binary:
        suffix = suffixes["binary"]
    else:
        suffix = suffixes["decimal"]

    base = 1024 if (gnu or binary) else 1000
    if isinstance(value, str):
        bytes_ = float(value)
    else:
        bytes_ = value

    abs_bytes = abs(bytes_)

    if abs_bytes == 1 and not gnu:
        return "%d Byte" % bytes_

    if abs_bytes < base:
        return ("%dB" if gnu else "%d Bytes") % bytes_

    for i, s in enumerate(suffix, 2):
        unit = base**i
        if abs_bytes < unit:
            break

    ret: str = format % (base * bytes_ / unit) + s
    return ret

ordinal

ordinal(value: 'float | str', gender: str = 'male') -> str

Converts an integer to its ordinal as a string.

Required packages: humanize

Example

Jinja call:

{{ 3 | ordinal }}
Result: 3rd

DocStrings

Examples:

>>> ordinal(1)
'1st'
>>> ordinal(1002)
'1002nd'
>>> ordinal(103)
'103rd'
>>> ordinal(4)
'4th'
>>> ordinal(12)
'12th'
>>> ordinal(101)
'101st'
>>> ordinal(111)
'111th'
>>> ordinal("something else")
'something else'
>>> ordinal([1, 2, 3]) == "[1, 2, 3]"
True

Parameters:

Name Type Description Default
value (int, str, float)

Integer to convert.

required
gender str

Gender for translations. Accepts either "male" or "female".

'male'

Returns:

Name Type Description
str str

Ordinal string.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def ordinal(value: NumberOrString, gender: str = "male") -> str:
    """Converts an integer to its ordinal as a string.

    For example, 1 is "1st", 2 is "2nd", 3 is "3rd", etc. Works for any integer or
    anything `int()` will turn into an integer. Anything else will return the output
    of str(value).

    Examples:
        ```pycon
        >>> ordinal(1)
        '1st'
        >>> ordinal(1002)
        '1002nd'
        >>> ordinal(103)
        '103rd'
        >>> ordinal(4)
        '4th'
        >>> ordinal(12)
        '12th'
        >>> ordinal(101)
        '101st'
        >>> ordinal(111)
        '111th'
        >>> ordinal("something else")
        'something else'
        >>> ordinal([1, 2, 3]) == "[1, 2, 3]"
        True

        ```

    Args:
        value (int, str, float): Integer to convert.
        gender (str): Gender for translations. Accepts either "male" or "female".

    Returns:
        str: Ordinal string.
    """
    try:
        if not math.isfinite(float(value)):
            return _format_not_finite(float(value))
        value = int(value)
    except (TypeError, ValueError):
        return str(value)
    if gender == "male":
        t = (
            P_("0 (male)", "th"),
            P_("1 (male)", "st"),
            P_("2 (male)", "nd"),
            P_("3 (male)", "rd"),
            P_("4 (male)", "th"),
            P_("5 (male)", "th"),
            P_("6 (male)", "th"),
            P_("7 (male)", "th"),
            P_("8 (male)", "th"),
            P_("9 (male)", "th"),
        )
    else:
        t = (
            P_("0 (female)", "th"),
            P_("1 (female)", "st"),
            P_("2 (female)", "nd"),
            P_("3 (female)", "rd"),
            P_("4 (female)", "th"),
            P_("5 (female)", "th"),
            P_("6 (female)", "th"),
            P_("7 (female)", "th"),
            P_("8 (female)", "th"),
            P_("9 (female)", "th"),
        )
    if value % 100 in (11, 12, 13):  # special case
        return f"{value}{t[0]}"
    return f"{value}{t[value % 10]}"

removeprefix

removeprefix(text: str, prefix: str) -> str

Return given prefix from text.

Example

Jinja call:

{{ "ccca" | removeprefix("c") }}
Result: cca

DocStrings

Parameters:

Name Type Description Default
text str

The text to strip the prefix from

required
prefix str

The prefix to remove

required
Source code in src/jinjarope/textfilters.py
31
32
33
34
35
36
37
38
def removeprefix(text: str, prefix: str) -> str:
    """Return given prefix from text.

    Args:
        text: The text to strip the prefix from
        prefix: The prefix to remove
    """
    return text.removeprefix(prefix)

removesuffix

removesuffix(text: str, suffix: str) -> str

Return given suffix from text.

Example

Jinja call:

{{ "acccc" | removesuffix("c") }}
Result: accc

DocStrings

Parameters:

Name Type Description Default
text str

The text to strip the suffix from

required
suffix str

The suffix to remove

required
Source code in src/jinjarope/textfilters.py
21
22
23
24
25
26
27
28
def removesuffix(text: str, suffix: str) -> str:
    """Return given suffix from text.

    Args:
        text: The text to strip the suffix from
        suffix: The suffix to remove
    """
    return text.removesuffix(suffix)

replace

replace(eval_ctx: 'EvalContext', s: str, old: str, new: str, count: Optional[int] = None) -> str

Return a copy of the value with all occurrences of a substring

Example

Jinja call:

{{ "abc" | replace("a", "x") }}
Result: xbc

Example

Jinja call:

{{ "aaaa" | replace("a", "b", 2) }}
Result: bbaa

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@pass_eval_context
def do_replace(
    eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
) -> str:
    """Return a copy of the value with all occurrences of a substring
    replaced with a new one. The first argument is the substring
    that should be replaced, the second is the replacement string.
    If the optional third argument ``count`` is given, only the first
    ``count`` occurrences are replaced:

    .. sourcecode:: jinja

        {{ "Hello World"|replace("Hello", "Goodbye") }}
            -> Goodbye World

        {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
            -> d'oh, d'oh, aaargh
    """
    if count is None:
        count = -1

    if not eval_ctx.autoescape:
        return str(s).replace(str(old), str(new), count)

    if (
        hasattr(old, "__html__")
        or hasattr(new, "__html__")
        and not hasattr(s, "__html__")
    ):
        s = escape(s)
    else:
        s = soft_str(s)

    return s.replace(soft_str(old), soft_str(new), count)

rstrip

rstrip(text: str, chars: str | None = None) -> str

Strip given chars from end of string.

Example

Jinja call:

{{ "abc " | rstrip }}
Result: abc

DocStrings

Parameters:

Name Type Description Default
text str

The text to strip the chars from

required
chars str | None

The chars to remove

None
Source code in src/jinjarope/textfilters.py
51
52
53
54
55
56
57
58
def rstrip(text: str, chars: str | None = None) -> str:
    """Strip given chars from end of string.

    Args:
        text: The text to strip the chars from
        chars: The chars to remove
    """
    return text.rstrip(chars)

safe

safe(value: str) -> markupsafe.Markup

Mark the value as safe which means that in an environment with automatic

Example

Jinja call:

{{ "<strong>Bold</strong>" | safe }}
Result: <strong>Bold</strong>

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1360
1361
1362
1363
1364
def do_mark_safe(value: str) -> Markup:
    """Mark the value as safe which means that in an environment with automatic
    escaping enabled this variable will not be escaped.
    """
    return Markup(value)

scientific

scientific(value: 'float | str', precision: int = 2) -> str

Return number in string scientific notation z.wq x 10ⁿ.

Required packages: humanize

Example

Jinja call:

{{ 0.3 | scientific }}
Result: 3.00 x 10⁻¹

DocStrings

Examples:

>>> scientific(float(0.3))
'3.00 x 10⁻¹'
>>> scientific(int(500))
'5.00 x 10²'
>>> scientific(-1000)
'-1.00 x 10³'
>>> scientific(1000, 1)
'1.0 x 10³'
>>> scientific(1000, 3)
'1.000 x 10³'
>>> scientific("99")
'9.90 x 10¹'
>>> scientific("foo")
'foo'
>>> scientific(None)
'None'

Parameters:

Name Type Description Default
value (int, float, str)

Input number.

required
precision int

Number of decimal for first part of the number.

2

Returns:

Name Type Description
str str

Number in scientific notation z.wq x 10ⁿ.

Source code in .venv/lib/python3.12/site-packages/humanize/number.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def scientific(value: NumberOrString, precision: int = 2) -> str:
    """Return number in string scientific notation z.wq x 10ⁿ.

    Examples:
        ```pycon
        >>> scientific(float(0.3))
        '3.00 x 10⁻¹'
        >>> scientific(int(500))
        '5.00 x 10²'
        >>> scientific(-1000)
        '-1.00 x 10³'
        >>> scientific(1000, 1)
        '1.0 x 10³'
        >>> scientific(1000, 3)
        '1.000 x 10³'
        >>> scientific("99")
        '9.90 x 10¹'
        >>> scientific("foo")
        'foo'
        >>> scientific(None)
        'None'

        ```

    Args:
        value (int, float, str): Input number.
        precision (int): Number of decimal for first part of the number.

    Returns:
        str: Number in scientific notation z.wq x 10ⁿ.
    """
    exponents = {
        "0": "⁰",
        "1": "¹",
        "2": "²",
        "3": "³",
        "4": "⁴",
        "5": "⁵",
        "6": "⁶",
        "7": "⁷",
        "8": "⁸",
        "9": "⁹",
        "-": "⁻",
    }
    try:
        value = float(value)
        if not math.isfinite(value):
            return _format_not_finite(value)
    except (ValueError, TypeError):
        return str(value)
    fmt = f"{{:.{str(int(precision))}e}}"
    n = fmt.format(value)
    part1, part2 = n.split("e")
    # Remove redundant leading '+' or '0's (preserving the last '0' for 10⁰).
    part2 = re.sub(r"^\+?(\-?)0*(.+)$", r"\1\2", part2)

    new_part2 = []
    for char in part2:
        new_part2.append(exponents[char])

    final_str = part1 + " x 10" + "".join(new_part2)

    return final_str

snake_case

snake_case(text: str) -> str

Convert given text to snake-case.

Example

Jinja call:

{{ " someText" | snake_case }}
Result: some_text

DocStrings

Parameters:

Name Type Description Default
text str

The string to convert

required
Source code in src/jinjarope/textfilters.py
74
75
76
77
78
79
80
81
82
83
def snake_case(text: str) -> str:
    """Convert given text to snake-case.

    Args:
        text: The string to convert
    """
    #  don't snake-case snakes.
    if "_" in text:
        return text
    return CASE_PATTERN.sub("_", text).lower()

striptags

striptags(value: 't.Union[str, HasHTML]') -> str

Strip SGML/XML tags and replace adjacent whitespace by one space.

Example

Jinja call:

{{ "<p>text</p>" | striptags }}
Result: text

Example

Jinja call:

{{ "<div><p>nested <b>tags</b></p></div>" | striptags }}
Result: nested tags

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1038
1039
1040
1041
1042
1043
def do_striptags(value: "t.Union[str, HasHTML]") -> str:
    """Strip SGML/XML tags and replace adjacent whitespace by one space."""
    if hasattr(value, "__html__"):
        value = t.cast("HasHTML", value).__html__()

    return Markup(str(value)).striptags()

title

title(s: str) -> str

Return a titlecased version of the value. I.e. words will start with

Example

Jinja call:

{{ "abc" | title }}
Result: Abc

Example

Jinja call:

{{ "hello world" | title }}
Result: Hello World

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
330
331
332
333
334
335
336
337
338
339
340
def do_title(s: str) -> str:
    """Return a titlecased version of the value. I.e. words will start with
    uppercase letters, all remaining characters are lowercase.
    """
    return "".join(
        [
            item[0].upper() + item[1:].lower()
            for item in _word_beginning_split_re.split(soft_str(s))
            if item
        ]
    )

trim

trim(value: str, chars: Optional[str] = None) -> str

Strip leading and trailing characters, by default whitespace.

Example

Jinja call:

{{ "  abc  " | trim }}
Result: abc

Example

Jinja call:

{{ "...text..." | trim(".") }}
Result: text

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1033
1034
1035
def do_trim(value: str, chars: t.Optional[str] = None) -> str:
    """Strip leading and trailing characters, by default whitespace."""
    return soft_str(value).strip(chars)

truncate

truncate(env: 'Environment', s: str, length: int = 255, killwords: bool = False, end: str = '...', leeway: Optional[int] = None) -> str

Return a truncated copy of the string. The length is specified

Example

Jinja call:

{{ "too long text" | truncate(5) }}
Result: to...

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
@pass_environment
def do_truncate(
    env: "Environment",
    s: str,
    length: int = 255,
    killwords: bool = False,
    end: str = "...",
    leeway: t.Optional[int] = None,
) -> str:
    """Return a truncated copy of the string. The length is specified
    with the first parameter which defaults to ``255``. If the second
    parameter is ``true`` the filter will cut the text at length. Otherwise
    it will discard the last word. If the text was in fact
    truncated it will append an ellipsis sign (``"..."``). If you want a
    different ellipsis sign than ``"..."`` you can specify it using the
    third parameter. Strings that only exceed the length by the tolerance
    margin given in the fourth parameter will not be truncated.

    .. sourcecode:: jinja

        {{ "foo bar baz qux"|truncate(9) }}
            -> "foo..."
        {{ "foo bar baz qux"|truncate(9, True) }}
            -> "foo ba..."
        {{ "foo bar baz qux"|truncate(11) }}
            -> "foo bar baz qux"
        {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
            -> "foo bar..."

    The default leeway on newer Jinja versions is 5 and was 0 before but
    can be reconfigured globally.
    """
    if leeway is None:
        leeway = env.policies["truncate.leeway"]

    assert length >= len(end), f"expected length >= {len(end)}, got {length}"
    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"

    if len(s) <= length + leeway:
        return s

    if killwords:
        return s[: length - len(end)] + end

    result = s[: length - len(end)].rsplit(" ", 1)[0]
    return result + end

upper

upper(s: str) -> str

Convert a value to uppercase.

Example

Jinja call:

{{ "sth" | upper }}
Result: STH

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
213
214
215
def do_upper(s: str) -> str:
    """Convert a value to uppercase."""
    return soft_str(s).upper()

wordcount

wordcount(s: str) -> int

Count the words in that string.

Example

Jinja call:

{{ "Some longer text" | wordcount }}
Result: 3

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
967
968
969
def do_wordcount(s: str) -> int:
    """Count the words in that string."""
    return len(_word_re.findall(soft_str(s)))

wordwrap

wordwrap(environment: 'Environment', s: str, width: int = 79, break_long_words: bool = True, wrapstring: Optional[str] = None, break_on_hyphens: bool = True) -> str

Wrap a string to the given width. Existing newlines are treated

Example

Jinja call:

{{ "sth" | wordwrap }}
Result: sth

Example

Jinja call:

{{ "a very long text" | wordwrap(width=5) }}
Result: a very long text

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
@pass_environment
def do_wordwrap(
    environment: "Environment",
    s: str,
    width: int = 79,
    break_long_words: bool = True,
    wrapstring: t.Optional[str] = None,
    break_on_hyphens: bool = True,
) -> str:
    """Wrap a string to the given width. Existing newlines are treated
    as paragraphs to be wrapped separately.

    :param s: Original text to wrap.
    :param width: Maximum length of wrapped lines.
    :param break_long_words: If a word is longer than ``width``, break
        it across lines.
    :param break_on_hyphens: If a word contains hyphens, it may be split
        across lines.
    :param wrapstring: String to join each wrapped line. Defaults to
        :attr:`Environment.newline_sequence`.

    .. versionchanged:: 2.11
        Existing newlines are treated as paragraphs wrapped separately.

    .. versionchanged:: 2.11
        Added the ``break_on_hyphens`` parameter.

    .. versionchanged:: 2.7
        Added the ``wrapstring`` parameter.
    """
    import textwrap

    if wrapstring is None:
        wrapstring = environment.newline_sequence

    # textwrap.wrap doesn't consider existing newlines when wrapping.
    # If the string has a newline before width, wrap will still insert
    # a newline at width, resulting in a short line. Instead, split and
    # wrap each paragraph individually.
    return wrapstring.join(
        [
            wrapstring.join(
                textwrap.wrap(
                    line,
                    width=width,
                    expand_tabs=False,
                    replace_whitespace=False,
                    break_long_words=break_long_words,
                    break_on_hyphens=break_on_hyphens,
                )
            )
            for line in s.splitlines()
        ]
    )