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 utilily.

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

to_bytes(s, encoding=None)

Convert str to bytes. If it is already bytes, do nothing.

Args:

s: str or bytes

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

Returns:

Type Description

bytes

Source code in k3str/str_ext.py
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
def to_bytes(s, encoding=None):
    """
    Convert str to bytes.  If it is already bytes, do nothing.

    Args:

        s: str or bytes

        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, 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
 8
 9
10
11
12
13
def to_utf8(s):
    """
    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 (张炎泼)