TypeError: 'str' object cannot be interpreted as an integer (tested fix)

TypeError: 'str' object cannot be interpreted as an integer means you passed a string, such as the result of input(), to a function that needs an int, most often range(). We reproduced it in Python 3.13 and tested the fix.

1. A str where an int is required

range(), chr() and other functions that need a whole number refuse strings, even "3". Sequence repetition and bytes() word the same mistake differently:

n = "3"                              # from input(), argv or a file
for expr in ["range(n)", "'ab' * n", "[0] * n", "bytes(n)", "chr(n)"]:
    try:
        print(f"{expr:10}", repr(eval(expr)))
    except TypeError as e:
        print(f"{expr:10} TypeError: {e}")

Output:

range(n)   TypeError: 'str' object cannot be interpreted as an integer
'ab' * n   TypeError: can't multiply sequence by non-int of type 'str'
[0] * n    TypeError: can't multiply sequence by non-int of type 'str'
bytes(n)   TypeError: string argument without an encoding
chr(n)     TypeError: 'str' object cannot be interpreted as an integer

2. The fix: int() at the boundary

n = "3"
print(list(range(int(n))), "ab" * int(n))
import sys
sys.argv = ["prog", "4"]
count = int(sys.argv[1])           # argv values are always str
print(list(range(count)))

Output:

[0, 1, 2] ababab
[0, 1, 2, 3]

input(), sys.argv, environment variables and CSV cells are always strings. Convert them once, where they enter your program. If the conversion itself fails, see invalid literal for int() with base 10.

3. argparse without type=int

import argparse
p = argparse.ArgumentParser()
p.add_argument("--n")                 # no type= -> str
p.add_argument("--m", type=int)       # converted for you
a = p.parse_args(["--n", "2", "--m", "2"])
print(repr(a.n), repr(a.m))
try:
    range(a.n)
except TypeError as e:
    print("TypeError:", e)
print(list(range(a.m)))

Output:

'2' 2
TypeError: 'str' object cannot be interpreted as an integer
[0, 1]

Without type=int, argparse hands you a string. Related: 'float' object cannot be interpreted as an integer and 'NoneType' object cannot be interpreted as an integer.

Frequently asked questions

How do I fix range(input()) TypeError?

Convert first: range(int(input())). input() always returns a str.

Why does argparse give me a string?

Arguments are str unless you pass type=int to add_argument().

Written with AI assistance. Measured on 2026-10-22 on Debian with Python 3.13.5: range, chr, bytes and sequence repetition with a str, int() conversion of argv, and argparse with and without type=int. Every block was run verbatim and its output pasted unedited. PlainHeaders is our extension; Python is free.