[Python] Type Error:'in <string>' requires string as left operand, not list

While studying Python scraping, when I was processing values, I got TypeError:'in <string>' requires string as left operand, not list, so I will leave a countermeasure in the memo

Cause of the error

I was trying to do a conditional branch to see if the corresponding string was found in the list obtained by Python.

if 'The character string you want to apply' in i:

Then I got this error

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

Countermeasures

Use list comprehension

False not in [i in 'The character string you want to apply'for i in A list containing the strings you want to search for]

Postscript

Quoted from @ shiracamus's comment! (Thank you!)

If you just want to make a judgment, you can use any function or all function.

>>> 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

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

Recommended Posts

[Python] Type Error:'in <string>' requires string as left operand, not list
Python2 string type
Python # string type
Python list is not a list
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
Python basic course (4 numeric type / character string type)
[Introduction to Udemy Python3 + Application] 16. List type
[Python] I tried to get the type name as a string from the type function