0

Code

text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
    if text in line:
        print(line.strip())
        cnt += 1
if cnt:
    print(cnt, "count")
else:
    print(text, "No data.")

Error:

Traceback (most recent call last):
  File "C:/Users/users/PycharmProjects/Mining/Test Folder/Test2.py", line 10, in <module>
    if text in line:
TypeError: 'in <string>' requires string as left operand, not list

Why this error occurs?

11
  • What is f here? Commented Mar 31, 2020 at 4:45
  • Because line is a string object and text is a list object, You are checking whether string contains list. Commented Mar 31, 2020 at 4:46
  • f means nothing.... Commented Mar 31, 2020 at 4:48
  • What do you want to do with above code ? What is the logic youare trying to implement. Commented Mar 31, 2020 at 4:53
  • There is a lot of data in the text file. When the data is loaded, if any of the four data I wrote matches, it show all the matching sentences. Commented Mar 31, 2020 at 4:55

2 Answers 2

0

The in keyword is used to check if a certain value is inside a collection.

If you want to know if line is in the list text, switch your operands:

text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
    if line in text: 
        print(line.strip())

If you want to know if any of the strings in the list text is inside/a substring of line:

text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
    if any([i in line for i in text]): 
        print(line.strip())
Sign up to request clarification or add additional context in comments.

1 Comment

Great to hear. If you can mark the question as resolved, it would be greatly appreciated. @이현규
-1

You need to understand how 'in' works in python.
Example:
> "abc" in ["pqr", "xyz", "abc"]
True
Here I am testing if string "abc" exist in the list mentioned on the right side of 'in' which is ["pqr", "xyz", "abc"]

But you are checking for the existence of a list (text in your code) inside another list (line in your code). Hence, as the error says 'in requires string as left operand' but you supplied a list.

2 Comments

This is not an answer. Please use comments to clarify things.
Hello @PrashantKumar, The question is Why this error occurs? and I answered that, explaining why that error occurs. Can you please let me know why this is not the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.