Pythonのコーディング中に発生した「unsupported operand type(s) for &: ‘str’ and ‘str’」のエラー対処方法をご紹介します。
unsupported operand type(s) for &: ‘str’ and ‘str’ エラー発生
Excelのシート名を変更しようとしたときに、エラーが発生しました。
エラー発生コード
9行目でエラーが発生しています。
import openpyxl
wb = openpyxl.load_workbook('C:/Users/xxx/Desktop/test/test.xlsx')
#ファイル内の全てのシートをループ
for ws in wb.worksheets:
if 'まとめ' in ws.title:
#シート名を変更
ws.title = '全体' & ws.title
エラー発生時のコマンドプロンプト
エラーとして表示されている英語の意味を調べてみました。
文字列型同士をandでつなげません、ってことみたいです。
・[unsupported operand type] → サポートされていないオペランドタイプ
・[ ‘str’ and ‘str’] → 文字列型 and 文字列型
解決方法
下記のように9行目のコードを修正したところ、エラー解決できました。
× → ws.title = ‘全体’ & ws.title
○ → ws.title = ‘全体’ + ws.title
import openpyxl
wb = openpyxl.load_workbook('C:/Users/xxx/Desktop/test/test.xlsx')
#ファイル内の全てのシートをループ
for ws in wb.worksheets:
if 'まとめ' in ws.title:
#シート名を変更
ws.title = '全体' + ws.title
文字と文字を「&」でつなげてはダメなのですね。。
無事プログラムを動かすことができました。
参考になりましたら幸いです。

【Python】よくあるエラーの原因と対処方法まとめ:38選
...