[python]文字と数字を"+"で連結するとエラー"TypeError: must be str, not int"

カテゴリ: python

pythonで文字列と数値を+演算子で連結すると、以下のようにTypeError: must be str, not intエラーが発生します

エラー例

プログラム

message = '1+1は' + (1+1) + 'です'
print(message)

エラー例

$ python test01.py

Traceback (most recent call last):
  File "test01.py", line 1, in <module>
    message = '1+1は' + (1+1) + 'です'
TypeError: must be str, not int

解決方法

このような場合はstr()で、数字を文字列にキャスト(変換)すれば良いです。

message = '1+1は' + str(1+1) + 'です'
print(message)

実行結果は下記の通りです

$ python test01.py
1+1は2です

Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です