MeWrite Docs

TypeError: can only concatenate str (not 'int') to str

Pythonで文字列と数値を+演算子で連結しようとした際のエラー

概要

Pythonで文字列と数値など、異なる型のオブジェクトを+演算子で連結しようとした際に発生するエラーです。

エラーメッセージ

TypeError: can only concatenate str (not "int") to str
TypeError: can only concatenate str (not "float") to str
TypeError: can only concatenate str (not "list") to str

原因

  1. 型の不一致: 文字列と数値を直接連結しようとしている
  2. 暗黙の型変換なし: Pythonは他の言語と異なり暗黙の型変換を行わない
  3. 変数の型の誤認識: 文字列だと思っていた変数が実は数値だった
  4. 関数の戻り値の型: 関数が期待と異なる型を返している

解決策

1. str()で明示的に変換

1
2
3
4
5
6
7
8
# Bad
age = 25
message = "I am " + age + " years old"  # TypeError

# Good
age = 25
message = "I am " + str(age) + " years old"
print(message)  # I am 25 years old

2. f-string(フォーマット済み文字列リテラル)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Good: f-string(Python 3.6+)
age = 25
message = f"I am {age} years old"
print(message)  # I am 25 years old

# 式も使用可能
price = 1000
tax = 0.1
message = f"Total: {price * (1 + tax):.2f}"
print(message)  # Total: 1100.00

3. format()メソッド

1
2
3
4
5
6
7
# Good
age = 25
message = "I am {} years old".format(age)
print(message)  # I am 25 years old

# 名前付きプレースホルダ
message = "Name: {name}, Age: {age}".format(name="John", age=25)

4. %演算子(古い形式)

1
2
3
4
5
6
7
# Good(古い形式だが動作する)
age = 25
message = "I am %d years old" % age
print(message)  # I am 25 years old

# 複数の値
message = "%s is %d years old" % ("John", 25)

5. join()でリストを連結

1
2
3
4
5
6
7
8
# Bad
items = ["apple", "banana", 3]
result = ", ".join(items)  # TypeError

# Good: すべてを文字列に変換
items = ["apple", "banana", 3]
result = ", ".join(str(item) for item in items)
print(result)  # apple, banana, 3

6. 型チェックを追加

1
2
3
4
5
6
def greet(name, age):
    if not isinstance(name, str):
        name = str(name)
    if not isinstance(age, (int, float)):
        raise ValueError("age must be a number")
    return f"Hello {name}, you are {age} years old"

よくある間違い

  • input()の戻り値が文字列であることを忘れて計算する
  • ファイルから読み込んだ数値を文字列として扱う
  • JSONから取得した値の型を確認しない

関連エラー

参考リンク

Python の他のエラー

最終更新: 2025-12-13