TheAlgorithms/Python · error · TypeError

plaintext must be a string

Error message

plaintext must be a string

What it means

Raised by autokey encrypt() when the plaintext argument is not a str. The cipher works character-by-character with ord()/string indexing on both plaintext and key, so non-string input is rejected by an isinstance check before any processing.

Source

Thrown at ciphers/autokey.py:39

    >>> encrypt("coffee is good as python", 2)
    Traceback (most recent call last):
        ...
    TypeError: key must be a string
    >>> encrypt("", "TheAlgorithms")
    Traceback (most recent call last):
        ...
    ValueError: plaintext is empty
    >>> encrypt("coffee is good as python", "")
    Traceback (most recent call last):
        ...
    ValueError: key is empty
    >>> encrypt(527.26, "TheAlgorithms")
    Traceback (most recent call last):
        ...
    TypeError: plaintext must be a string
    """
    if not isinstance(plaintext, str):
        raise TypeError("plaintext must be a string")
    if not isinstance(key, str):
        raise TypeError("key must be a string")

    if not plaintext:
        raise ValueError("plaintext is empty")
    if not key:
        raise ValueError("key is empty")

    key += plaintext
    plaintext = plaintext.lower()
    key = key.lower()
    plaintext_iterator = 0
    key_iterator = 0
    ciphertext = ""
    while plaintext_iterator < len(plaintext):
        if (
            ord(plaintext[plaintext_iterator]) < 97
            or ord(plaintext[plaintext_iterator]) > 122

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a str: encrypt(str(plaintext), key) if the value is a number or other printable object.
  2. Decode bytes first: encrypt(data.decode('utf-8'), key).
  3. Check argument order — plaintext is the first parameter for encrypt().

Example fix

# before
encrypt(527.26, 'TheAlgorithms')  # TypeError: plaintext must be a string

# after
encrypt(str(527.26), 'TheAlgorithms')
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(plaintext, str):
    plaintext = str(plaintext)

Type guard

def is_str(v: object) -> bool:
    return isinstance(v, str)

Try / catch

try:
    encrypt(p, k)
except TypeError:
    p = str(p)
    ciphertext = encrypt(p, k)

Prevention

When it happens

Trigger: Calling encrypt(527.26, 'TheAlgorithms'), encrypt(None, 'key'), encrypt(['a'], 'key'), or any non-str first argument.

Common situations: Passing numbers or bytes from upstream data pipelines, or calling encrypt/decrypt with swapped argument order (ciphertext/key confusion).

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/44ebf2fc909babaa. Report an issue: GitHub.