TheAlgorithms/Python · error · TypeError
key must be a string
Error message
key must be a string
What it means
Raised by autokey encrypt() when the key argument is not a str. Alongside the plaintext check, the function requires both operands to be strings because it concatenates key += plaintext and indexes both with ord() arithmetic.
Source
Thrown at ciphers/autokey.py:41
...
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
):
ciphertext += plaintext[plaintext_iterator]View on GitHub (pinned to f5988cc097)
Solutions
- Pass a string key: encrypt(text, str(2)) or better, an actual keyword like 'TheAlgorithms'.
- If key arrives as bytes, decode it: key.decode('utf-8').
- Remember the order: encrypt(plaintext, key) — plaintext first.
Example fix
# before
encrypt('hello', 2) # TypeError: key must be a string
# after
encrypt('hello', 'coffee') Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(key, str) or not key:
raise ValueError('a non-empty string key is required') Type guard
def is_nonempty_str(v: object) -> bool:
return isinstance(v, str) and len(v) > 0 Prevention
- Use keyword-style string keys ('TheAlgorithms'), never numeric keys.
- Validate both operands once with a shared helper before encrypt/decrypt.
When it happens
Trigger: Calling encrypt('coffee is good as python', 2), or passing None/bytes/list as the key.
Common situations: Using a numeric key out of habit from Caesar/Vigenère examples, or swapping the argument order so a number lands in the key slot.
Related errors
- plaintext 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/49e6ad2df8572a4d.
Report an issue: GitHub.