TypeError: sequence item 0: expected str instance, int found
TypeError: sequence item 0: expected str instance, int found in Python means str.join() only joins strings. One of the items, the first one here, is a number.
How do I fix TypeError: sequence item 0: expected str instance, int found?
TypeError: sequence item 0: expected str instance, int found means str.join() was given a number. join() only accepts strings and will not convert for you. Convert each item inside the call: ", ".join(str(x) for x in items), or ", ".join(map(str, items)). The item number shows which position failed first.
- 1. Read the item numbersequence item 1 means the second element is not a string. Print the list to see its value and type.
- 2. Convert inside joinWrite "".join(str(d) for d in digits) or wrap single values, as in [name, str(age)].
- 3. Watch for NoneNoneType found means a missing value. Filter with (p for p in parts if p) instead of joining None.
What does TypeError: sequence item 0: expected str instance, int found mean?
", ".join(items) builds one string from many and refuses to convert anything for you, because silently turning values into text hides bugs. The message gives the position of the first non-string item and its type: item 0, an int.
Why does TypeError: sequence item 0: expected str instance, int found happen?
1. Joining numbers
Digits, IDs and scores are ints until you convert them.
Breaks
pin = "".join([1, 2, 3, 4])Works
pin = "".join(str(d) for d in [1, 2, 3, 4])2. Joining mixed data
Rows from a file or database mix text and numbers.
Breaks
line = ", ".join([name, age])Works
line = ", ".join([name, str(age)])3. Joining values that might be None
A missing field is None, not an empty string.
Breaks
full = " ".join([first, middle, last])Works
full = " ".join(p for p in [first, middle, last] if p)How to find it in your own code
Convert inside the join: ", ".join(str(x) for x in items), or map(str, items). If some items can be None, filter them out first rather than printing the word None.
Try it: fix this bug
easybuild_pin([1, 2, 3, 4]) crashes: TypeError: sequence item 0: expected str instance, int found.
def build_pin(digits):
return "".join(digits)Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.