Skip to main content

How to Resolve Python Error "TypeError: can only concatenate str (not "...") to str"

The TypeError: can only concatenate str (not "...") to str is a very common Python error. It occurs when you try to use the addition operator (+) to join a string (str) with an object of a different, incompatible data type (like int, list, float, NoneType, bytes, dict, set, or NumPy types). Python requires both operands to be strings for concatenation using +.

This guide explains why this error happens and provides the standard solutions for combining strings with various other data types.

Understanding the Error: String Concatenation Rules

In Python, the addition operator (+) has different meanings depending on the types of operands:

  • For numbers (int, float): It performs arithmetic addition (3 + 5 is 8).
  • For lists: It performs list concatenation ([1, 2] + [3, 4] is [1, 2, 3, 4]).
  • For strings: It performs string concatenation ("hello" + " " + "world" is "hello world").

Crucially, for string concatenation, both operands must be strings. You cannot directly "add" a number, list, dictionary, None, or bytes object to a string using the + operator.

The Primary Cause: Type Mismatch with + Operator

The error occurs because you provide a string on one side of the + operator and an object of a different type (the one mentioned in the error message, like "int", "list", "NoneType") on the other side.

# Error Scenario Examples
greeting = "Value: "
number = 100
my_list = [1, 2]
flag = None

try:
# ⛔️ TypeError: can only concatenate str (not "int") to str
result = greeting + number
except TypeError as e:
print(e)

try:
# ⛔️ TypeError: can only concatenate str (not "list") to str
result = greeting + my_list
except TypeError as e:
print(e)

try:
# ⛔️ TypeError: can only concatenate str (not "NoneType") to str
result = greeting + flag
except TypeError as e:
print(e)
note

Similar errors occur for float, dict, set, bytes, numpy types etc.

Solution 1: Convert Non-String Object to String using str() (Universal)

The most common and universal solution is to explicitly convert the non-string object into its string representation using the built-in str() function before performing the concatenation.

Example: Integer (int)

count = 50
message = "Items found: " + str(count) # ✅ Convert int to str
print(message) # Output: Items found: 50

Example: Float (float) / NumPy Float (numpy.float64)

import numpy as np
price = 19.99
price_np = np.float64(19.99)
label = "Price: $" + str(price) # ✅ Convert float to str
label_np = "NumPy Price: $" + str(price_np) # ✅ Convert numpy.float64 to str

print(label) # Output: Price: $19.99
print(label_np) # Output: NumPy Price: $19.99

Example: List (list)

items = ["A", "B", "C"]
description = "Available items: " + str(items) # ✅ Convert list to str
print(description) # Output: Available items: ['A', 'B', 'C']

Example: Dictionary (dict)

config = {"port": 8080, "host": "localhost"}
info = "Config details: " + str(config) # ✅ Convert dict to str
print(info) # Output: Config details: {'port': 8080, 'host': 'localhost'}

Example: Set (set)

unique_ids = {10, 20, 30}
id_report = "Unique IDs found: " + str(unique_ids) # ✅ Convert set to str
print(id_report) # Output: Unique IDs found: {10, 20, 30} (order may vary)

Example: None (NoneType)

user_status = None
status_message = "User status: " + str(user_status) # ✅ Convert None to str ('None')
print(status_message) # Output: User status: None

Example: NumPy Integer (numpy.int64)

import numpy as np

item_count = np.int64(1000)
report = "Total items: " + str(item_count) # ✅ Convert numpy.int64 to str
print(report) # Output: Total items: 1000
note

Using str() works reliably for converting most standard Python objects and many library objects (like NumPy types) into a string suitable for concatenation.

f-strings (formatted string literals) provide a more concise and often more readable way to embed variables and expressions within strings. They automatically handle the conversion of many types (including numbers, lists, dicts, None) to their string representations.

name = "Alice"
age = 30
scores = [95, 88, 100]
settings = {'enabled': True}
status = None

# ✅ F-string handles conversion automatically
output = f"User: {name}, Age: {age}, Scores: {scores}, Settings: {settings}, Status: {status}"

print(output)
# Output: User: Alice, Age: 30, Scores: [95, 88, 100], Settings: {'enabled': True}, Status: None
note

f-strings are the preferred method for string formatting and embedding values in modern Python code (version 3.6 and later).

Solution 3: Specific Handling for bytes Objects

Bytes objects (b'...') represent sequences of raw bytes, while strings represent sequences of Unicode characters. They cannot be directly concatenated using +. You need to either decode the bytes into a string or encode the string into bytes.

Decode Bytes to String (.decode())

prefix = "Data: "
byte_data = b'raw bytes here'

# ✅ Decode bytes to string (assuming UTF-8 or appropriate encoding)
combined_str = prefix + byte_data.decode('utf-8')
print(combined_str) # Output: Data: raw bytes here

Encode String to Bytes (.encode())

byte_prefix = b"Header: "
string_data = "Some Text"

# ✅ Encode string to bytes (assuming UTF-8)
combined_bytes = byte_prefix + string_data.encode('utf-8')
print(combined_bytes) # Output: b'Header: Some Text'
note

Choose the conversion (decode or encode) based on whether you want the final result to be a string or a bytes object.

Special Case: Intending Arithmetic Addition (Numeric Types)

If you encountered the error with int, float, or NumPy numeric types, but your actual goal was mathematical addition, then you need to convert the string part to a number using int() or float().

string_num = "100"
value = 50

# Incorrect for addition: '100' + 50 # Raises TypeError

# ✅ Correct for addition: Convert string to int first
total = int(string_num) + value
print(f"Arithmetic sum: {total}") # Output: Arithmetic sum: 150

string_float = "25.5"
value_float = 10.0
total_float = float(string_float) + value_float
print(f"Float sum: {total_float}") # Output: Float sum: 35.5

Output:

Arithmetic sum: 150
Float sum: 35.5
note

Remember that input() always returns a string, so conversion is necessary for calculations.

Special Case: Accessing Elements within Containers (Lists/Dicts)

If the error involved a list or dictionary, perhaps you intended to concatenate the string with an element or value from within the container, not the container itself.

prefix = "Item: "
items_list = ["Apple", "Banana"]
item_dict = {"code": "X1", "name": "Widget"}

# Incorrect: prefix + items_list # Raises TypeError
# Incorrect: prefix + item_dict # Raises TypeError

# ✅ Correct: Access element/value first, then concatenate (may need str())
first_item = prefix + items_list[0] # String + String
print(first_item) # Output: Item: Apple

item_name = prefix + item_dict['name'] # String + String
print(item_name) # Output: Item: Widget

item_code = prefix + str(item_dict['code']) # String + str(value) - needs str() if value isn't string
# (Using f-string is cleaner here: f"{prefix}{item_dict['code']}")
print(item_code) # Output: Item: X1

Output:

Item: Apple
Item: Widget
Item: X1

Debugging: Identifying the Types (type(), isinstance())

When the TypeError occurs:

  1. Look at the line number mentioned in the error.
  2. Identify the two variables/values being added with +.
  3. Use print(type(variable_name)) or print(isinstance(variable_name, str)) for each variable to confirm their types. One will be str, and the other will be the type mentioned in the error message. This confirms the type mismatch.

Conclusion

The TypeError: can only concatenate str (not "X") to str clearly indicates an attempt to use the + operator between a string and a non-string type X.

The main solutions are:

  1. Convert to String: Use str(non_string_object) to convert the other object to its string representation before concatenating.
  2. Use F-Strings: Employ f-strings (e.g., f"{my_string} {my_number} {my_list}") for embedding variables and expressions, as they handle the necessary string conversions automatically (for most types). (Recommended for Python 3.6+).
  3. Decode/Encode bytes: Use .decode() or .encode() when dealing specifically with bytes objects.
  4. Convert String to Number: If arithmetic addition was intended, use int() or float() on the string operand.
  5. Access Container Elements: If working with lists/dicts, access the specific element/value first before concatenating (converting to str if needed).

Choosing the correct approach based on the non-string type and your intended operation will resolve this common Python error.