Cristian Avendaño
Cristian Avendaño

Reputation: 477

Check if string is in list with python

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!

Upvotes: 0

Views: 185

Answers (2)

everspader
everspader

Reputation: 1710

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

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

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.

Upvotes: 0

Related Questions