0

I'm new to python, and I'm trying to check if a String is inside a list.

I have these two variables:

 new_filename: 'SOLICITUDES2_20201206.DAT'  (str type)
 

and

 downloaded_files:
   [['SOLICITUDES-20201207.TXT'], ['SOLICITUDES-20201015.TXT'], ['SOLICITUDES2_20201206.DAT']] (list type)

for checking if the string is inside the list, I'm using the following:

   if new_filename in downloaded_files:
       print(new_filename,'downloaded')

and I never get inside the if.

But if I do the same, but with hard-coded text, it works:

    if ['SOLICITUDES2_20201206.DAT'] in downloaded_files_list:
        print(new_filename,'downloaded')

What am I doing wrong?

Thanks!

2 Answers 2

1

Your downloaded_files is a list of lists. A list can contain anything insider it, numbers, list, dictionaries, strings and etc. If you are trying to find if your string is inside the list, the if statement will only look for identical matches, i.e., strings.

What I suggest you do is get all the strings into a list instead of a list of lists. You can do it using list comprehension:

downloaded_files = [['SOLICITUDES-20201207.TXT'], ['SOLICITUDES-20201015.TXT'], ['SOLICITUDES2_20201206.DAT']]

downloaded_files_list = [file[0] for file in downloaded_files]

Then, your if statement should work:

new_filename = 'SOLICITUDES2_20201206.DAT'

if new_filename in downloaded_files_list:
   print(new_filename,'downloaded')
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is asking if a string is in a list of lists of a single string each, which is why it doesn't find any.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.