TheAlgorithms/Python · error · TypeError
Input must be a string
Error message
Input must be a string
What it means
Raised by count_vowels in strings/count_vowels.py when s is not a str. The function counts characters from the fixed vowel set 'aeiouAEIOU' by iterating the string, so any non-string (int, list, None) is rejected up front with TypeError. Unlike several neighbors in this repo, this one correctly uses TypeError for a type mismatch.
Source
Thrown at strings/count_vowels.py:25
Examples:
>>> count_vowels("hello world")
3
>>> count_vowels("HELLO WORLD")
3
>>> count_vowels("123 hello world")
3
>>> count_vowels("")
0
>>> count_vowels("a quick brown fox")
5
>>> count_vowels("the quick BROWN fox")
5
>>> count_vowels("PYTHON")
1
"""
if not isinstance(s, str):
raise TypeError("Input must be a string")
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
if __name__ == "__main__":
from doctest import testmod
testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Convert at the boundary: count_vowels(str(text)).
- Handle None explicitly: count_vowels(text or '').
- Decode bytes first: count_vowels(blob.decode('utf-8')) if handling raw byte input.
Example fix
# before
count_vowels(payload.get('comment')) # comment missing -> None
# after
count_vowels(payload.get('comment') or '') Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(s, str):
raise TypeError(f'expected str, got {type(s).__name__}')
count = count_vowels(s) Type guard
def is_str(value) -> bool:
return isinstance(value, str) Try / catch
try:
n = count_vowels(text)
except TypeError:
n = 0 if text is None else count_vowels(str(text)) Prevention
- Handle optional text fields with (text or '') before passing to string helpers.
- Decode bytes to str at the I/O boundary.
- count_vowels correctly raises TypeError, so a plain `except TypeError` is reliable here.
When it happens
Trigger: count_vowels(123); count_vowels(['a', 'e']); count_vowels(None) when an optional text field was never provided.
Common situations: Optional fields defaulting to None; JSON numbers where text was expected; passing bytes instead of str (bytes is also rejected).
Related errors
- Expected string as input, found {type(input_str)}
- 'float' object cannot be interpreted as an integer
- 'float' object cannot be interpreted as an integer
- iterations must be defined as integers
- All weights must be integers but got weight of type {type(wt
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/25808e12ec003827.
Report an issue: GitHub.