Skip to content

k3str

Action-CI Documentation Status Package

String operation utilities for encoding conversion.

k3str is a component of pykit3 project: a python3 toolkit set.

Installation

pip install k3str

Quick Start

import k3str

# Convert string to bytes
b = k3str.to_bytes("我")
print(repr(b))  # b'\xe6\x88\x91'

# Convert to UTF-8 bytes
utf8_bytes = k3str.to_utf8("hello")

# Get default encoding
print(k3str.default_encoding)

API Reference

k3str

k3str is a collection of string operation utilities.

>>> repr(to_bytes('我'))
"b'\\xe6\\x88\\x91'"

to_bytes(s, encoding=None)

Convert str to bytes. If it is already bytes, do nothing. A bytearray or memoryview is copied into bytes.

Parameters:

Name Type Description Default
s str | bytes | bytearray | memoryview

the value to convert.

required
encoding str

the encoding to encode str. If it is None, system default encoding is used.

None

Returns:

Type Description
bytes

bytes

Source code in k3str/str_ext.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def to_bytes(s: object, encoding: str | None = None) -> bytes:
    """
    Convert str to bytes.  If it is already bytes, do nothing.
    A ``bytearray`` or ``memoryview`` is copied into bytes.

    Args:
        s(str | bytes | bytearray | memoryview): the value to convert.

        encoding(str):
            the encoding to encode str.
            If it is None, system default encoding is used.

    Returns:
        bytes
    """

    if encoding is None:
        encoding = default_encoding

    if isinstance(s, bytes):
        return s

    if isinstance(s, (bytearray, memoryview)):
        return bytes(s)

    if isinstance(s, str):
        return bytes(s, encoding)

    return bytes(str(s), encoding)

to_utf8(s)

Convert str to utf8 bytes. It is an alias of to_bytes(s, encoding='utf-8').

Source code in k3str/str_ext.py
 6
 7
 8
 9
10
11
def to_utf8(s: object) -> bytes:
    """
    Convert str to utf8 bytes.
    It is an alias of ``to_bytes(s, encoding='utf-8')``.
    """
    return to_bytes(s, encoding="utf-8")

License

The MIT License (MIT) - Copyright (c) 2015 Zhang Yanpo (张炎泼)