import base64


def encode(data, chunklen=6, linelen=78):
    """
    Encode data with base64 and format it.

    Arguments:
        data: String to be encoded.
        chunklen: Number of bytes in a chunk, defaults to 6.
        linelen: Length of a line, defaults to 78 characters.

    Returns:
        The base64 encoded data.
    """
    length = len(data)
    n = int(linelen // (4 * chunklen / 3))
    chunks = [
        base64.b64encode(data[j : j + chunklen]).decode("ascii")
        for j in range(0, length, chunklen)
    ]
    lines = [" ".join(chunks[i : i + n]) for i in range(0, len(chunks), n)]
    return "\n".join(lines)