python 数値を文字列として結合する

python 数値を文字列として結合する

pythonで、str関数を利用して数値をまず文字列に変換して、数値と文字列として結合するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

結合

str()関数を使用すれば、数値を文字列としてと扱うことが可能です。

以下の場合だと「3」と出力されますが、

s = 1 + 1 + 1

print(s)
# 3

str()関数を使用すると「1」を文字列として扱うことができるので「111」と出力されます。

s = str(1) + str(1) + str(1)

print(s)
# 111

当然、文字列と結合も可能です。

s = '令和' + str(2) + '年'

print(s)
# 令和2年

数値をそのまま結合する場合は、エラーとなります。

s = '令和' + 2 + '年'

print(s)
# TypeError: can only concatenate str (not "int") to str