紹介
Pythonは、+
演算子を使用して文字列の連結をサポートしています。他の多くのプログラミング言語では、文字列と整数(または他のプリミティブデータ型)を連結すると、言語がそれらを文字列に変換してから連結します。
しかし、Pythonでは、+
演算子を使用して文字列と整数を連結しようとすると、ランタイムエラーが発生します。
例
文字列(str
)と整数(int
)を+
演算子を使用して連結する例を見てみましょう。
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + current_year)
期待される出力は、次の文字列です:Year is 2018
。しかし、このコードを実行すると、次のランタイムエラーが発生します:
Traceback (most recent call last):
File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str
では、Pythonでstr
とint
をどのように連結するのでしょうか?この操作を実行するためには、さまざまな方法があります。
前提条件
このチュートリアルを完了するためには、以下が必要です:
- Python 3のインストールに関する知識とPythonでのコーディングに関する知識が必要です。 Python 3でのコーディング方法シリーズまたはPythonのためのVS Codeを使用します。
このチュートリアルはPython 3.9.6でテストされました。
str()
関数の使用
int
をstr()
関数に渡すことができ、str
に変換されます:
print(current_year_message + str(current_year))
current_year
整数は文字列として返されます:年は2018年です
。
%
補間演算子の使用
printfスタイルの文字列フォーマットを使用して変換仕様に値を渡すことができます:
print("%s%s" % (current_year_message, current_year))
current_year
整数は文字列に補間されます:年は2018年です
。
str.format()
関数を使用する
文字列と整数の連結には、str.format()
関数も使用できます。
print("{}{}".format(current_year_message, current_year))
current_year
整数は文字列に型変換されます:年は2018です
。
f-stringsを使用する
Python 3.6以降のバージョンを使用している場合、f-stringsも使用できます。
print(f'{current_year_message}{current_year}')
current_year
整数は文字列に補間されます:年は2018です
。
結論
完全なPythonスクリプトや他のPythonの例については、GitHubリポジトリをご覧ください。
Source:
https://www.digitalocean.com/community/tutorials/python-concatenate-string-and-int