Python · Trimming and Translating

Trimming and Translating

import stringzilla 6.0.0-rc.1 · 91a27bdd

§ Trimming

  • strip(chars=whitespace) — remove leading and trailing bytes that are in chars.
  • lstrip(chars=whitespace) — remove only leading bytes.
  • rstrip(chars=whitespace) — remove only trailing bytes.

With no argument, the default character set is ASCII whitespace. Pass a byteset to trim an arbitrary set of bytes.

import stringzilla as sz

assert sz.String("  hi  ").strip() == "hi"
assert sz.String("xxhi").lstrip("x") == "hi"
assert sz.String("hi!!").rstrip("!") == "hi"

§ Translating

translate(table, inplace=False, start=0, end=len) applies a byte-to-byte mapping in a single pass. table is either a 256-byte string/bytes lookup table or a dict mapping bytes to bytes, spelled as characters below U+0100. A str input is translated as its UTF-8 bytes and decoded back, so a table that breaks the encoding raises UnicodeDecodeError. With inplace=True the buffer is rewritten in place and None is returned; otherwise a new bytes/str is returned. A non-256-byte table raises ValueError; a non-string, non-dict table raises TypeError.

import stringzilla as sz

assert sz.String("abc").translate({"a": "A"}) == b"Abc"

table = bytes(range(256)).translate(bytes.maketrans(b"abc", b"ABC"))
assert sz.String("cabbage").translate(table) == b"CABBAge"

Strings.translate(table) takes the same tables and maps every string of a collection in one call, returning a new Strings, as Escaping and Normalizing Collections describes.

§ Decoding

decode(encoding='utf-8', errors='strict') decodes the bytes to a Python str, mirroring bytes.decode.

import stringzilla as sz

assert sz.String("abc").decode() == "abc"

API

Functions

lstripRemove leading characters from a string.
__init__.pyi:956 ↗
def lstrip(
    text: _StringLike,
    chars: _StringLike | None = None,
    *,
    capabilities: Capability | None = None,
) -> String

Returns: String: A new string with leading characters removed.

Parameters

text_StringLikeThe string object.
chars_StringLike | NoneCharacters to remove, defaulting to whitespace.
capabilitiesCapability | NoneCapabilities to run, defaulting to the CPU's enabled ones.

Examples

>>> sz.String('  hi').lstrip() == 'hi'
True
rstripRemove trailing characters from a string.
__init__.pyi:971 ↗
def rstrip(
    text: _StringLike,
    chars: _StringLike | None = None,
    *,
    capabilities: Capability | None = None,
) -> String

Returns: String: A new string with trailing characters removed.

Parameters

text_StringLikeThe string object.
chars_StringLike | NoneCharacters to remove, defaulting to whitespace.
capabilitiesCapability | NoneCapabilities to run, defaulting to the CPU's enabled ones.

Examples

>>> sz.String('hi  ').rstrip() == 'hi'
True
stripRemove leading and trailing characters from a string.
__init__.pyi:986 ↗
def strip(
    text: _StringLike,
    chars: _StringLike | None = None,
    *,
    capabilities: Capability | None = None,
) -> String

Returns: String: A new string with leading and trailing characters removed.

Parameters

text_StringLikeThe string object.
chars_StringLike | NoneCharacters to remove, defaulting to whitespace.
capabilitiesCapability | NoneCapabilities to run, defaulting to the CPU's enabled ones.

Examples

>>> sz.String('  hi  ').strip() == 'hi'
True
decodeDecode the bytes into a Unicode string with a given encoding.
__init__.pyi:1161 ↗
def decode(
    text: _StringLike,
    encoding: str = 'utf-8',
    errors: str = 'strict',
) -> str

Returns: str: The decoded Unicode string. Raises: UnicodeDecodeError: If decoding fails.

Parameters

text_StringLikeThe string object.
encodingstrThe encoding to use, defaulting to 'utf-8'.
errorsstrError handling scheme, defaulting to 'strict'.

Examples

>>> sz.String('abc').decode() == 'abc'
True
write_toWrite the string to a file.
__init__.pyi:1178 ↗
def write_to(text: _StringLike, filename: str) -> None

Returns: None.

Parameters

text_StringLikeThe string object.
filenamestrThe file path to write to.

Examples

>>> import os, tempfile
>>> path = os.path.join(tempfile.gettempdir(), 'sz_demo.bin')
>>> sz.String('payload').write_to(path)
offset_withinReturn the raw byte offset of this StringZilla string within a larger StringZilla string.
__init__.pyi:1193 ↗
def offset_within(text: _StringLike, larger: String) -> int

Returns: int: The byte offset where 'self' is found within 'larger', or -1 if not found.

Parameters

text_StringLikeThe substring.
largerStringThe larger string to search within.

Examples

>>> big = sz.String('hello world')
>>> big[6:].offset_within(big)
6
translatePerform transformation of a string using a look-up table.
__init__.pyi:1208 ↗
def translate(
    text: _StringLike,
    table: str | bytes | dict[str, str],
    inplace: bool = False,
    start: int = 0,
    end: int | None = None,
    *,
    capabilities: Capability | None = None,
) -> None | str | bytes

Returns: Union[None, str, bytes]: If inplace is False, a translated copy of the [start, end) slice is returned, otherwise None. Raises: ValueError: If the table is not 256 bytes long, or a dict names a character above U+00FF. UnicodeDecodeError: If a str input translates into malformed UTF-8. TypeError: If the table is not a string or dictionary.

Parameters

text_StringLikeThe string object.
tablestr | bytes | dict[str, str]A 256-byte string, or a dict mapping characters below U+0100 to such.
inplaceboolIf True, the string is modified in place, defaulting to False.
startintThe starting index for translation, defaulting to 0.
endint | NoneThe ending index for translation, defaulting to the string length.
capabilitiesCapability | NoneCapabilities to run, defaulting to the CPU's enabled ones.

Examples

>>> sz.String('abc').translate({'a': 'A'}) == b'Abc'
True