5.

【Pythonエラー】can only concatenate str (not "NoneType") to str

編集
この記事の要点
  • TypeError: can only concatenate str (not "NoneType") to strNone を文字列と + で連結したエラー
  • 原因: 関数が return を書き忘れた / メソッドが None を返した / 変数が初期化されていない
  • 対処 ①: 連結前に None チェック
  • 対処 ②: str() で明示的に文字列化
  • 対処 ③: f-string や format() なら None も "None" として表示される(エラーにならない)

 

エラーの意味

Python で以下のようなコードを書くと発生:

name = None
greeting = "Hello, " + name
# TypeError: can only concatenate str (not "NoneType") to str

Python の + 演算子は同じ型同士でしか連結できません。文字列 "Hello, "None を直接 + するとこのエラーになります。

よくある原因パターン

パターン 1: 関数の return 書き忘れ

def get_name():
    name = "Alice"
    # return を書き忘れ → 戻り値は None

result = "User: " + get_name()
# TypeError: ...

# 修正:
def get_name():
    name = "Alice"
    return name  # ← 追加

パターン 2: dict.get() で存在しないキー

user = {"name": "Alice"}
greeting = "Hello, " + user.get("nickname")
# get() は存在しないキーで None を返す → TypeError

# 修正:
greeting = "Hello, " + user.get("nickname", "ゲスト")  # デフォルト値

パターン 3: 環境変数が未設定

import os
host = os.environ.get("HOST")  # 環境変数 HOST が未設定なら None
url = "http://" + host + "/api"
# TypeError

# 修正:
host = os.environ.get("HOST", "localhost")  # デフォルト値

パターン 4: 関数呼び出しが副作用のみ(list.append 等)

items = []
result = "Items: " + str(items.append("a"))
# list.append() は None を返す → str(None) は "None" だが、生 None を + すると TypeError

# 修正:
items.append("a")
result = "Items: " + str(items)

パターン 5: 正規表現で match しない

import re
m = re.match(r"(\d+)", "abc")  # マッチしないと None
value = "Found: " + m.group(1)
# m is None → AttributeError もしくは TypeError

# 修正:
m = re.match(r"(\d+)", "abc")
if m:
    value = "Found: " + m.group(1)
else:
    value = "Not found"

対処方法

方法 1: None チェック

name = get_name()
if name is None:
    name = "ゲスト"
greeting = "Hello, " + name

# または or 演算子で短く
greeting = "Hello, " + (name or "ゲスト")

方法 2: str() で明示変換

name = get_name()  # None かもしれない
greeting = "Hello, " + str(name)
# → "Hello, None" (エラーにならない)

方法 3: f-string を使う(推奨)

name = None
greeting = f"Hello, {name}"
# → "Hello, None" (エラーにならない、自動で str 化)

方法 4: format() メソッド

name = None
greeting = "Hello, {}".format(name)
# → "Hello, None"

類似エラー(要注意)

エラーメッセージ意味
can only concatenate str (not "int") to strint を文字列に連結(str(int_val) で変換)
can only concatenate list (not "str") to listlist と str を連結(list + [str] で対応)
unsupported operand type(s) for +: 'NoneType' and 'str'左辺が None の場合(順序逆)
AttributeError: 'NoneType' object has no attribute ...None に対してメソッド呼び出し

予防策

  • 型ヒント (Type Hints) を使う: 関数の戻り値型を明示すれば IDE が None の可能性を警告
  • mypy で静的型チェック: Optional[str] 等を使い分けて事前に検出
  • None を返す関数は明示的にチェック: dict.get, re.match, list.find
  • 初期値を None にしない: 空文字 "" や空リスト [] を初期値にする
  • f-string を活用: 連結より f-string の方が None 耐性がある

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. ModuleNotFoundError: No module named '~'; '~' is not a package
  2. pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available
  3. ...AppData/Local/Microsoft/WindowsApps/python: Permission denied
  4. 【pycharm】connecting to console が終わらない
  5. can only concatenate str (not "NoneType") to str
  6. can only concatenate str (not "datetime.datetime") to str