Skip to content

# cmd2.string_utils

## `` cmd2.string_utils

Provides string utility functions.

This module offers a collection of string utility functions built on the Rich library. These utilities are designed to correctly handle strings with ANSI style sequences and full-width characters (like those used in CJK languages).

### `` align

    align(val, align, width=None, character=' ')

Align string to a given width.

There are convenience wrappers around this function: align_left(), align_center(), and align_right()

PARAMETER | DESCRIPTION
--- | ---
`val` | string to align TYPE: `str`
`align` | one of "left", "center", or "right". TYPE: `AlignMethod`
`width` | Desired width. Defaults to width of the terminal. TYPE: `int | None` DEFAULT: `None`
`character` | Character to pad with. Defaults to " ". TYPE: `str` DEFAULT: `' '`

Source code in `cmd2/string_utils.py`

    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36

    def align(
        val: str,
        align: AlignMethod,
        width: int | None = None,
        character: str = " ",
    ) -> str:
        """Align string to a given width.

        There are convenience wrappers around this function: align_left(), align_center(), and align_right()

        :param val: string to align
        :param align: one of "left", "center", or "right".
        :param width: Desired width. Defaults to width of the terminal.
        :param character: Character to pad with. Defaults to " ".

        """
        if width is None:
            width = ru.console_width()

        text = Text.from_ansi(val)
        text.align(align, width=width, character=character)
        return ru.rich_text_to_string(text)

### `` align_left

    align_left(val, width=None, character=' ')

Left-align string to a given width.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to align TYPE: `str`
`width` | Desired width. Defaults to width of the terminal. TYPE: `int | None` DEFAULT: `None`
`character` | Character to pad with. Defaults to " ". TYPE: `str` DEFAULT: `' '`

Source code in `cmd2/string_utils.py`

    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51

    def align_left(
        val: str,
        width: int | None = None,
        character: str = " ",
    ) -> str:
        """Left-align string to a given width.

        :param val: string to align
        :param width: Desired width. Defaults to width of the terminal.
        :param character: Character to pad with. Defaults to " ".

        """
        return align(val, "left", width=width, character=character)

### `` align_center

    align_center(val, width=None, character=' ')

Center-align string to a given width.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to align TYPE: `str`
`width` | Desired width. Defaults to width of the terminal. TYPE: `int | None` DEFAULT: `None`
`character` | Character to pad with. Defaults to " ". TYPE: `str` DEFAULT: `' '`

Source code in `cmd2/string_utils.py`

    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66

    def align_center(
        val: str,
        width: int | None = None,
        character: str = " ",
    ) -> str:
        """Center-align string to a given width.

        :param val: string to align
        :param width: Desired width. Defaults to width of the terminal.
        :param character: Character to pad with. Defaults to " ".

        """
        return align(val, "center", width=width, character=character)

### `` align_right

    align_right(val, width=None, character=' ')

Right-align string to a given width.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to align TYPE: `str`
`width` | Desired width. Defaults to width of the terminal. TYPE: `int | None` DEFAULT: `None`
`character` | Character to pad with. Defaults to " ". TYPE: `str` DEFAULT: `' '`

Source code in `cmd2/string_utils.py`

    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81

    def align_right(
        val: str,
        width: int | None = None,
        character: str = " ",
    ) -> str:
        """Right-align string to a given width.

        :param val: string to align
        :param width: Desired width. Defaults to width of the terminal.
        :param character: Character to pad with. Defaults to " ".

        """
        return align(val, "right", width=width, character=character)

### `` stylize

    stylize(val, style)

Apply an ANSI style to a string, preserving any existing styles.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to be styled TYPE: `str`
`style` | style instance or style definition to apply. TYPE: `StyleType`

RETURNS | DESCRIPTION
--- | ---
`str` | the stylized string

Source code in `cmd2/string_utils.py`

    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94

    def stylize(val: str, style: StyleType) -> str:
        """Apply an ANSI style to a string, preserving any existing styles.

        :param val: string to be styled
        :param style: style instance or style definition to apply.
        :return: the stylized string
        """
        # Convert to a Rich Text object to parse and preserve existing ANSI styles.
        text = Text.from_ansi(val)
        text.stylize(style)
        return ru.rich_text_to_string(text)

### `` strip_style

    strip_style(val)

Strip all ANSI style sequences from a string.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to be stripped TYPE: `str`

RETURNS | DESCRIPTION
--- | ---
`str` | the stripped string

Source code in `cmd2/string_utils.py`

     97
     98
     99
    100
    101
    102
    103

    def strip_style(val: str) -> str:
        """Strip all ANSI style sequences from a string.

        :param val: string to be stripped
        :return: the stripped string
        """
        return ru.ANSI_STYLE_SEQUENCE_RE.sub("", val)

### `` str_width

    str_width(val)

Return the display width of a string.

This is intended for single-line strings. Replace tabs with spaces before calling this.

PARAMETER | DESCRIPTION
--- | ---
`val` | the string being measured TYPE: `str`

RETURNS | DESCRIPTION
--- | ---
`int` | width of the string when printed to the terminal

Source code in `cmd2/string_utils.py`

    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116

    def str_width(val: str) -> int:
        """Return the display width of a string.

        This is intended for single-line strings.
        Replace tabs with spaces before calling this.

        :param val: the string being measured
        :return: width of the string when printed to the terminal
        """
        text = Text.from_ansi(val)
        return text.cell_len

### `` is_quoted

    is_quoted(val)

Check if a string is quoted.

PARAMETER | DESCRIPTION
--- | ---
`val` | the string being checked for quotes TYPE: `str`

RETURNS | DESCRIPTION
--- | ---
`bool` | True if a string is quoted

Source code in `cmd2/string_utils.py`

    119
    120
    121
    122
    123
    124
    125
    126
    127

    def is_quoted(val: str) -> bool:
        """Check if a string is quoted.

        :param val: the string being checked for quotes
        :return: True if a string is quoted
        """
        from . import constants

        return len(val) > 1 and val[0] == val[-1] and val[0] in constants.QUOTES

### `` quote

    quote(val)

Quote a string.

Source code in `cmd2/string_utils.py`

    130
    131
    132
    133
    134

    def quote(val: str) -> str:
        """Quote a string."""
        quote = "'" if '"' in val else '"'

        return quote + val + quote

### `` quote_if_needed

    quote_if_needed(val)

Quote a string if it contains spaces and isn't already quoted.

Source code in `cmd2/string_utils.py`

    137
    138
    139
    140
    141
    142

    def quote_if_needed(val: str) -> str:
        """Quote a string if it contains spaces and isn't already quoted."""
        if is_quoted(val) or ' ' not in val:
            return val

        return quote(val)

### `` strip_quotes

    strip_quotes(val)

Strip outer quotes from a string.

Applies to both single and double quotes.

PARAMETER | DESCRIPTION
--- | ---
`val` | string to strip outer quotes from TYPE: `str`

RETURNS | DESCRIPTION
--- | ---
`str` | same string with potentially outer quotes stripped

Source code in `cmd2/string_utils.py`

    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155

    def strip_quotes(val: str) -> str:
        """Strip outer quotes from a string.

         Applies to both single and double quotes.

        :param val:  string to strip outer quotes from
        :return: same string with potentially outer quotes stripped
        """
        if is_quoted(val):
            val = val[1:-1]
        return val

### `` norm_fold

    norm_fold(val)

Normalize and casefold Unicode strings for saner comparisons.

PARAMETER | DESCRIPTION
--- | ---
`val` | input unicode string TYPE: `str`

RETURNS | DESCRIPTION
--- | ---
`str` | a normalized and case-folded version of the input string

Source code in `cmd2/string_utils.py`

    158
    159
    160
    161
    162
    163
    164
    165
    166

    def norm_fold(val: str) -> str:
        """Normalize and casefold Unicode strings for saner comparisons.

        :param val: input unicode string
        :return: a normalized and case-folded version of the input string
        """
        import unicodedata

        return unicodedata.normalize("NFC", val).casefold()