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]) > 122View on GitHub (pinned to f5988cc097)
Solutions
- Pass a str: encrypt(str(plaintext), key) if the value is a number or other printable object.
- Decode bytes first: encrypt(data.decode('utf-8'), key).
- 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
- Keep argument order documented: encrypt(plaintext, key).
- Decode bytes to str at the system boundary.
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
- key must be a string
- ciphertext must be a string
- operation can not be conducted on an object of type {type(nu
- Input value must be an 'int' type
- plain must contain only lowercase letters (a-z)
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/44ebf2fc909babaa.
Report an issue: GitHub.