Pythonで文字列を結合(join, +演算子)
この記事では、Pythonで文字列を結合する2つの主要な方法である、joinメソッドと+演算子について解説します。それぞれの方法の特徴、パフォーマンス、そして使い分けについて詳しく説明します。
目次
joinメソッドによる結合
joinメソッドは、リストやタプルの要素を文字列で結合する際に最も効率的な方法です。
strings = ['This', 'is', 'a', 'sentence.']
result = ' '.join(strings)
print(result) # 出力: This is a sentence.
上記の例では、スペース(' ')を区切り文字として使用し、リストの要素を結合しています。区切り文字は任意の文字列に設定可能です。
strings = ['apple', 'banana', 'cherry']
result = ','.join(strings)
print(result) # 出力: apple,banana,cherry
numbers = ['1', '2', '3']
result = ''.join(numbers)
print(result) # 出力: 123
+演算子による結合
+演算子を使用して文字列を結合することもできますが、joinメソッドに比べて効率性が劣ります。
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 出力: HelloWorld
複数の文字列を結合する場合は、+演算子を複数回使用することになり、コードが冗長になります。
str1 = 'Python'
str2 = 'is'
str3 = 'great'
result = str1 + ' ' + str2 + ' ' + str3
print(result) # 出力: Python is great
パフォーマンス比較
joinメソッドは、特に多数の文字列を結合する場合、+演算子よりもはるかに高速です。これは、joinメソッドが内部的により効率的な方法で文字列操作を行うためです。
# 1000個の文字列を結合する例
import time
strings = [str(i) for i in range(1000)]
start_time = time.time()
result_join = ''.join(strings)
end_time = time.time()
print(f"joinメソッドの実行時間: {end_time - start_time:.6f}秒")
result_plus = ''
start_time = time.time()
for s in strings:
result_plus += s
end_time = time.time()
print(f"+演算子の実行時間: {end_time - start_time:.6f}秒")
どちらを使うべきか?
多くの場合、joinメソッドを使用することをお勧めします。joinメソッドは、コードが簡潔で、パフォーマンスも優れているためです。+演算子は、ごく少数の文字列を結合する場合にのみ適しています。
関連記事
- Pythonで文字列を分割(split, rsplit, splitlines)
- Pythonで文字列を検索(find, rfind, index, rindex)
- Pythonで文字列を中央寄せ・左寄せ・右寄せ(center, ljust, rjust)
- Pythonで文字列をフォーマット(format, f文字列 (Python 3.6以降), %演算子)
- Pythonで文字列の先頭と末尾が特定の文字列か判定(startswith, endswith)
- Pythonで文字列を置換(replace, translate, re.sub)
- Pythonで文字列の大文字・小文字を変換(upper, lower, capitalize, title, swapcase)
- Pythonで文字列の先頭・末尾の空白を削除(strip, lstrip, rstrip)
- Pythonで文字列をスライスで部分抽出
- Pythonで文字列の出現回数をカウント(count)