LoginSignup
1
1

More than 3 years have passed since last update.

【Python】TypeError: 'in <string>' requires string as left operand, not list

Last updated at Posted at 2020-07-28

Pythonのスクレイピングを勉強中、値の加工をしていたらTypeError: 'in <string>' requires string as left operand, not listが出たので、メモで対策を残します

エラーが出た原因

Pythonで取得したlistに、該当する文字列がまれているかの、条件分岐をやろうとしていました。

if '該当させたい文字列' in i:

そしたらこのエラーが出た

TypeError: 'in <string>' requires string as left operand, not list

対策

リスト内包表記を使う

False not in [i in '該当させたい文字列' for i in 検索したい文字列の入ったリスト]

追記

@shiracamus さんのコメントから引用!(ありがとうございます!)

判定するだけなら any関数 や all関数 を使うといいですよ。

>>> any('test' in item for item in ['hoge', 'fuge', 'hogetestfuge'])
True
>>> all('test' in item for item in ['hoge', 'fuge', 'hogetestfuge'])
False
>>> all('test' in item for item in ['testhoge', 'fugetest', 'hogetestfuge'])
True

参考
https://pg-chain.com/python-in
https://ai-inter1.com/python-if-in/
https://kuzunoha-ne.hateblo.jp/entry/2019/02/15/213000

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1