python エラー「TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’」が発生した場合の対処法

pythonで、エラー「TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’」が発生した場合の対処法を記述してます。文字列と数値で演算しようとした際などに発生します。pythonのバージョンは3.10.0を使用してます。
環境
- OS windows11 home 64bit
- python 3.10.0
エラー全文
以下のコードで発生
num1 = 10
num2 = '10'
num1 + num2
エラー全文
num1 + num2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
原因
文字列と数値を演算しようとしたため
対処法
数値同士で演算するか、
num1 = 10
num2 = 10
num1 + num2
数値型に変換して、演算を行う。
num1 = 10
num2 = '10'
num1 + int(num2)
-
前の記事
Dart 文字列を置換する 2023.03.11
-
次の記事
mac windowsとファイル共有を行う 2023.03.12
コメントを書く