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.
defapnumber(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. """importmathtry:ifnotmath.isfinite(float(value)):return_format_not_finite(float(value))value=int(value)except(TypeError,ValueError):returnstr(value)ifnot0<=value<10:returnstr(value)return_(_APNUMBER_WORDS[value])
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:
Type
Description
str | None
str | None: Formatted number, or None when value is None.
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.
defclamp(value:float|None,format:str|Callable[[float],str]="{:}",floor:float|None=None,ceil:float|None=None,floor_token:str="<",ceil_token:str=">",)->str|None:"""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, None): Input number, or `None` to return `None`. 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 | None: Formatted number, or `None` when `value` is `None`. 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. """importmathifvalueisNone:returnNoneifnotmath.isfinite(value):return_format_not_finite(value)iffloorisnotNoneandvalue<floor:value=floortoken=floor_tokenelifceilisnotNoneandvalue>ceil:value=ceiltoken=ceil_tokenelse:token=""ifisinstance(format,str):returntoken+format.format(value)ifcallable(format):returntoken+format(value)msg=("Invalid format. Must be either a valid formatting string, or a function ""that accepts value and returns a string.")raiseValueError(msg)
defdo_forceescape(value:"t.Union[str, HasHTML]")->Markup:"""Enforce HTML escaping. This will probably double escape variables."""ifhasattr(value,"__html__"):value=t.cast("HasHTML",value).__html__()returnescape(str(value))
deffractional(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. """importmathtry:number=float(value)ifnotmath.isfinite(number):return_format_not_finite(number)except(TypeError,ValueError):returnstr(value)fromfractionsimportFractionwhole_number=int(number)frac=Fraction(number-whole_number).limit_denominator(1000)numerator=frac.numeratordenominator=frac.denominatorifdenominator==1:# The fractional part reduced to a whole number: either an integer# was passed in (e.g. 1 or 1.0000, giving 0/1), or the fractional part# rounded up to 1/1 (e.g. 2.9999999). Fold it into the integer part# instead of emitting a degenerate "0/1" or "2 1/1".returnf"{whole_number+numerator:.0f}"ifnotwhole_number:returnf"{numerator:.0f}/{denominator:.0f}"# int() truncates toward zero, so for a negative number both# whole_number and numerator carry the minus sign, which prints as# "-1 -3/10". The sign already rides on the whole part; absorb it# from the fractional part so the result reads as a normal mixed# fraction.returnf"{whole_number:.0f}{abs(numerator):.0f}/{denominator:.0f}"
defdo_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``. """ifisinstance(width,str):indention=widthelse:indention=" "*widthnewline="\n"ifisinstance(s,Markup):indention=Markup(indention)newline=Markup(newline)s+=newline# this quirk is necessary for splitlines methodifblank:rv=(newline+indention).join(s.splitlines())else:lines=s.splitlines()rv=lines.pop(0)iflines:rv+=newline+newline.join(indention+lineiflineelselineforlineinlines)iffirst:rv=indention+rvreturnrv
defintcomma(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. """importmaththousands_sep=thousands_separator()decimal_sep=decimal_separator()try:ifisinstance(value,str):value=value.replace(thousands_sep,"").replace(decimal_sep,".")ifnotmath.isfinite(float(value)):return_format_not_finite(float(value))if"."invalue:value=float(value)else:value=int(value)elifnotisinstance(value,int):ifnotmath.isfinite(float(value)):return_format_not_finite(float(value))float(value)except(TypeError,ValueError):returnstr(value)ifndigitsisnotNone:result=f"{value:,.{ndigits}f}"else:result=f"{value:,}"ifthousands_sep!=","ordecimal_sep!=".":result=result.translate(str.maketrans(",.",thousands_sep+decimal_sep))returnresult
defintword(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", 1_200_000 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`. """importmathtry:ifnotmath.isfinite(float(value)):return_format_not_finite(float(value))value=int(value)except(TypeError,ValueError):returnstr(value)ifvalue<0:value*=-1negative_prefix="-"else:negative_prefix=""ifvalue<powers[0]:returnf"{negative_prefix}{value}"ordinal=bisect.bisect_right(powers,value)largest_ordinal=ordinal==len(powers)# Consider the biggest power of 10 that is smaller than valueordinal-=1power=powers[ordinal]chopped=value/powerrounded_value=float(format%chopped)ifnotlargest_ordinalandrounded_value==powers[ordinal+1]//power:# After rounding, we end up just at the next power. Compare against the# integer ratio between the two powers instead of ``rounded_value * power``:# for values above ~10**22 the latter is evaluated in floating point and# no longer equals the exact ``powers[ordinal + 1]``, so the carry was# silently skipped (e.g. 10**24 - 1 rendered as "1000.0 sextillion").ordinal+=1rounded_value=1.0singular,plural=human_powers[ordinal]unit=_ngettext(singular,plural,math.ceil(rounded_value))decimal_sep=decimal_separator()number=(format%rounded_value).replace(".",decimal_sep)returnf"{negative_prefix}{number}{unit}"
deflower_camel_case(text:str)->str:"""Convert given text to lower-camel-case. Args: text: The string to convert """# do nothing if nothing to camelif"_"notintext:returntextfirst,*others=text.split("_")return"".join([first.lower(),*map(str.title,others)])
deflstrip(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 """returntext.lstrip(chars)
defnaturalsize(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. """ifgnu:suffix=suffixes["gnu"]elifbinary:suffix=suffixes["binary"]else:suffix=suffixes["decimal"]base=1024if(gnuorbinary)else1000bytes_=float(value)abs_bytes=abs(bytes_)ifabs_bytes==1andnotgnu:return_("%d Byte")%int(bytes_)ifabs_bytes<base:returnf"{int(bytes_)}B"ifgnuelse_("%d Bytes")%int(bytes_)frommathimportlogexp=int(min(log(abs_bytes,base),len(suffix)))# The suffix is chosen from the unrounded byte count, but `format` rounds the# mantissa afterward; rounding can push it up to `base` (e.g. 999999 is# 999.999 kB, which formats to "1000.0 kB"). When that happens and a larger# suffix is available, step up one suffix so the result reads "1.0 MB".ifexp<len(suffix)andabs(float(format%(abs_bytes/(base**exp))))>=base:exp+=1space=""ifgnuelse" "ret:str=format%(bytes_/(base**exp))+space+_(suffix[exp-1])returnret
defordinal(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. """importmathtry:ifnotmath.isfinite(float(value)):return_format_not_finite(float(value))value=int(value)except(TypeError,ValueError):returnstr(value)gender="male"ifgender=="male"else"female"digit=0ifvalue%100in(11,12,13)elsevalue%10returnf"{value}{P_(*_ORDINAL_SUFFIXES[gender][digit])}"
defremoveprefix(text:str,prefix:str)->str:"""Return given prefix from text. Args: text: The text to strip the prefix from prefix: The prefix to remove """returntext.removeprefix(prefix)
defremovesuffix(text:str,suffix:str)->str:"""Return given suffix from text. Args: text: The text to strip the suffix from suffix: The suffix to remove """returntext.removesuffix(suffix)
@pass_eval_contextdefdo_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 """ifcountisNone:count=-1ifnoteval_ctx.autoescape:returnstr(s).replace(str(old),str(new),count)if(hasattr(old,"__html__")orhasattr(new,"__html__")andnothasattr(s,"__html__")):s=escape(s)else:s=soft_str(s)returns.replace(soft_str(old),soft_str(new),count)
defrstrip(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 """returntext.rstrip(chars)
defdo_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. """returnMarkup(value)
scientific(value: 'NumberOrString', 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'
defscientific(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ⁿ. """importmathtry:value=float(value)ifnotmath.isfinite(value):return_format_not_finite(value)except(ValueError,TypeError):returnstr(value)fmt=f"{{:.{int(precision)}e}}"n=fmt.format(value)part1,part2=n.split("e")# Normalise exponent: int() strips the "+" sign and leading zeros,# while preserving "-" and a single "0" for 10⁰.returnpart1+" x 10"+str(int(part2)).translate(_SUPERSCRIPT_TRANS)
defsnake_case(text:str)->str:"""Convert given text to snake-case. Args: text: The string to convert """# don't snake-case snakes.if"_"intext:returntextreturnCASE_PATTERN.sub("_",text).lower()
defdo_striptags(value:"t.Union[str, HasHTML]")->str:"""Strip SGML/XML tags and replace adjacent whitespace by one space."""ifhasattr(value,"__html__"):value=t.cast("HasHTML",value).__html__()returnMarkup(str(value)).striptags()
defdo_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()foritemin_word_beginning_split_re.split(soft_str(s))ifitem])
defdo_trim(value:str,chars:t.Optional[str]=None)->str:"""Strip leading and trailing characters, by default whitespace."""returnsoft_str(value).strip(chars)
@pass_environmentdefdo_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. """ifleewayisNone:leeway=env.policies["truncate.leeway"]assertlength>=len(end),f"expected length >= {len(end)}, got {length}"assertleeway>=0,f"expected leeway >= 0, got {leeway}"iflen(s)<=length+leeway:returnsifkillwords:returns[:length-len(end)]+endresult=s[:length-len(end)].rsplit(" ",1)[0]returnresult+end
@pass_environmentdefdo_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. """importtextwrapifwrapstringisNone: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.returnwrapstring.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,))forlineins.splitlines()])