Skip to content

st

FG

Bases: ColorANSI

Foreground Color

BG

Bases: ColorANSI

Background Color

ST

Bases: ColorANSI

Style

sf

A collection of functions that can be used to filter strings.

filename classmethod

filename(filename: str, replace_with: str = '') -> str

Removes or replaces characters that are not allowed to be in a filename.

Source code in stdl/st.py
@classmethod
def filename(cls, filename: str, replace_with: str = "") -> str:
    """
    Removes or replaces characters that are not allowed to be in a filename.
    """
    return remove(filename, chars='|?*<>:"\\', replace_with=replace_with)

filepath classmethod

filepath(filepath: str, replace_with: str = '') -> str

Removes or replaces characters that are not allowed to be in a filepath.

Source code in stdl/st.py
@classmethod
def filepath(cls, filepath: str, replace_with: str = "") -> str:
    """
    Removes or replaces characters that are not allowed to be in a filepath.
    """
    if not filepath:
        return ""
    dirname, filename = os.path.split(filepath)
    filename = sf.filename(filename, replace_with)
    dirname = remove(dirname, '|?*<>:"')
    return f"{dirname}{os.sep}{filename}"

ascii classmethod

ascii(s: str, replace_with: str = '')

Removes or replaces non-ASCII characters from the string.

Source code in stdl/st.py
@classmethod
def ascii(cls, s: str, replace_with: str = ""):
    """
    Removes or replaces non-ASCII characters from the string.
    """
    return keep(s, ASCII, replace_with)

colored

colored(text: str, color: ForegroundColor | None = None, background: BackgroundColor | None = None, style: Style | None = None)

Returns the text with ansi color, background color and text style codes.

Parameters:

Name Type Description Default
text str

The text that should be colorized.

required
color str

The color to use for the text.

None
background str

The color to use for the background.

None
style str

The style to use for the text.

None

Returns:

Name Type Description
str

The colorized text.

Source code in stdl/st.py
def colored(
    text: str,
    color: ForegroundColor | None = None,
    background: BackgroundColor | None = None,
    style: Style | None = None,
):
    """
    Returns the text with ansi color, background color and text style codes.

    Args:
        text (str): The text that should be colorized.
        color (str, optional): The color to use for the text.
        background (str, optional): The color to use for the background.
        style (str, optional): The style to use for the text.

    Returns:
        str: The colorized text.
    """
    if NO_COLOR or not stdout.isatty():
        return text
    color = _get_ansi_value(color, FG)  # type: ignore
    background = _get_ansi_value(background, BG)  # type: ignore
    style = _get_ansi_value(style, ST)  # type: ignore
    return f"{color}{background}{style}{text}{ST.RESET}"
terminal_link(uri: str, label: str | None = None, color: ForegroundColor = 'white', background: BackgroundColor | None = None, style: Style | None = None)

Returns a hyperlink that can be used in terminals.

NOTE

Hyperlinks are not supported in all terminals. For more information visit https://github.com/Alhadis/OSC8-Adoption/ and https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda

Parameters:

Name Type Description Default
uri str

The URI of the link.

required
label str

The label of the link. Defaults to the URI.

None
color str

The color of the link. Defaults to white.

'white'
background str

The background color of the link.

None
style str

The style of the link.

None

Returns:

Name Type Description
str

The link as a string.

Source code in stdl/st.py
def terminal_link(
    uri: str,
    label: str | None = None,
    color: ForegroundColor = "white",
    background: BackgroundColor | None = None,
    style: Style | None = None,
):
    """
    Returns a hyperlink that can be used in terminals.

    NOTE:
        Hyperlinks are not supported in all terminals.
        For more information visit
        <https://github.com/Alhadis/OSC8-Adoption/>
        and
        <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>

    Args:
        uri (str): The URI of the link.
        label (str, optional): The label of the link. Defaults to the URI.
        color (str, optional): The color of the link. Defaults to white.
        background (str, optional): The background color of the link.
        style (str, optional): The style of the link.

    Returns:
        str: The link as a string.
    """
    if label is None:
        label = uri

    if stdout.isatty():
        link = f"\033]8;;{uri}\033\\{label}\033]8;;\033\\"
    else:
        link = uri
    link = colored(link, color, background, style)
    return link

remove

remove(s: str, chars: str | set, replace_with: str = '') -> str

Remove or replace characters in a string.

Parameters:

Name Type Description Default
s str

Input string.

required
chars str | set

Characters to remove

required
replace_with str

If provided, replace the characters with this value.

''
Source code in stdl/st.py
def remove(s: str, chars: str | set, replace_with: str = "") -> str:
    """
    Remove or replace characters in a string.

    Args:
        s (str): Input string.
        chars (str | set): Characters to remove
        replace_with (str, optional): If provided, replace the characters with this value.

    """
    string = []
    chars = set(chars)
    for c in s:
        if c not in chars:
            string.append(c)
        else:
            if replace_with:
                string.append(replace_with)
    return "".join(string)

keep

keep(s: str, chars: str | set, replace_with: str = '') -> str

Keep provided characters in a string. Remove or replace others.

Parameters:

Name Type Description Default
s str

Input string

required
chars str | set

Characters to keep

required
replace_with str

If provided, replace other characters with this value.

''
Source code in stdl/st.py
def keep(s: str, chars: str | set, replace_with: str = "") -> str:
    """
    Keep provided characters in a string. Remove or replace others.

    Args:
        s (str): Input string
        chars (str | set): Characters to keep
        replace_with (str, optional): If provided, replace other characters with this value.

    """
    string = []
    chars = set(chars)
    for c in s:
        if c in chars:
            string.append(c)
        else:
            if replace_with:
                string.append(replace_with)
    return "".join(string)

snake_case

snake_case(s: str) -> str

Converts a given string to snake_case.

Source code in stdl/st.py
def snake_case(s: str) -> str:
    """Converts a given string to snake_case."""
    return "_".join(
        re.sub(
            "([A-Z][a-z]+)",
            r" \1",
            re.sub("([A-Z]+)", r" \1", s.replace("-", " ")),
        ).split()
    ).lower()

camel_case

camel_case(s: str) -> str

Converts a given string to camelCase.

Source code in stdl/st.py
def camel_case(s: str) -> str:
    """Converts a given string to camelCase."""
    s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "")
    return s[0].lower() + s[1:]

kebab_case

kebab_case(s: str) -> str

Converts a given string to kebab-case.

Source code in stdl/st.py
def kebab_case(s: str) -> str:
    """Converts a given string to kebab-case."""
    RE_WORDS = r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+"
    RE_SEP = r"(\s|_|-)+"
    return "-".join(
        re.sub(
            RE_SEP,
            " ",
            re.sub(
                RE_WORDS,
                lambda mo: " " + mo.group(0).lower(),
                s,
            ),
        ).split()
    )

wrapped

wrapped(text: str, width: int, newline: str = '\n') -> str

Wraps the given text to a specified width and separates lines with the given newline character.

Source code in stdl/st.py
def wrapped(text: str, width: int, newline: str = "\n") -> str:
    """Wraps the given text to a specified width and separates lines with the given newline character."""
    return newline.join(textwrap.wrap(text, width=width))

len_without_ansi

len_without_ansi(s: str) -> int

Returns the length of the string without the ANSI codes.

Source code in stdl/st.py
def len_without_ansi(s: str) -> int:
    """Returns the length of the string without the ANSI codes."""
    ascii_codes = re.findall(r"\x1b\[[0-9;]*[m]", s)
    codes_len = sum(len(code) for code in ascii_codes)
    return len(s) - codes_len

ansi_ljust

ansi_ljust(s: str, width: int, fillchar: str = ' ') -> str

ljust function that takes into account the length of the ANSI codes in the string.

Parameters:

Name Type Description Default
s str

The string to be left justified.

required
width int

The width of the string.

required
fillchar str

The character to fill the string with. Defaults to " ".

' '
Source code in stdl/st.py
def ansi_ljust(s: str, width: int, fillchar: str = " ") -> str:
    """
    ljust function that takes into account the length of the ANSI codes in the string.

    Args:
        s (str): The string to be left justified.
        width (int): The width of the string.
        fillchar (str, optional): The character to fill the string with. Defaults to " ".
    """
    ascii_codes = re.findall(r"\x1b\[[0-9;]*[m]", s)
    codes_len = sum(len(code) for code in ascii_codes)
    new_width = width + codes_len
    return s.ljust(new_width, fillchar)

ansi_rjust

ansi_rjust(s: str, width: int, fillchar: str = ' ') -> str

rjust function that takes into account the length of the ANSI codes in the string.

Parameters:

Name Type Description Default
s str

The string to be right justified.

required
width int

The width of the string.

required
fillchar str

The character to fill the string with. Defaults to " ".

' '
Source code in stdl/st.py
def ansi_rjust(s: str, width: int, fillchar: str = " ") -> str:
    """
    rjust function that takes into account the length of the ANSI codes in the string.

    Args:
        s (str): The string to be right justified.
        width (int): The width of the string.
        fillchar (str, optional): The character to fill the string with. Defaults to " ".
    """
    ascii_codes = re.findall(r"\x1b\[[0-9;]*[m]", s)
    codes_len = sum(len(code) for code in ascii_codes)
    new_width = width + codes_len
    return s.rjust(new_width, fillchar)

ansi_strip

ansi_strip(r: str) -> str

Remove ANSI escape codes from a string.

Source code in stdl/st.py
def ansi_strip(r: str) -> str:
    """
    Remove ANSI escape codes from a string.
    """
    ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
    return ansi_escape.sub("", r)