Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search contains string in array python

Tags:

python

arrays

I have a string like this search = 'hello' and I need check all array to see if any contains hello.
For example:

"hello" == "123hello123" | true
"hello" == "aasdasdasd123hello123" | true
"hello" == "123123hello" | true

I need something like search for my code

list_all_files_in_google_drive - it my all file name array

filename - name file, which need to check if exist in google drive or not

if not any(file['title'] == filename for file in list_all_files_in_google_drive):
   print('file not exist')

my code doesn't work because it works like this:

"hello" == "123hello123" | false
"hello" == "aasdasdasd123hello123" | false
"hello" == "123123hello" | false
"hello" == "hello" | true

and I need it to work like this:

"hello" == "123hello123" | true
"hello" == "aasdasdasd123hello123" | true
"hello" == "123123hello" | true
"hello" == "hello" | true

UPD:

I checked operator in and it does not output true

filename = 'hello'
list = ['123hello123', 'aasdasdasd123hello123', '123123hello']
if filename in list:
    print('true')
like image 423
r1299597 Avatar asked Jun 13 '26 09:06

r1299597


2 Answers

Just go through each string in the list with a simple loop, and check if 'hello' exists with the pythons membership in operator:

lst = ['123hello123', 'aasdasdasd123hello123', '123123hello']

for x in lst:
    if 'hello' in x:
        print('true')

Which outputs:

true
true
true

Or if you want to check all() the strings in lst at once:

if all('hello' in x for x in lst):
    print('true')

Or if you want to check if any() of the strings in lst at once:

if any('hello' in x for x in lst):
    print('true')

Both of which will output:

true

Note: Using list as a variable name as shown in your question is not a good idea here, as it shadows the builtin function list(). Also returning a boolean True or False here is fine, not need to return a string form of these.

like image 107
RoadRunner Avatar answered Jun 15 '26 22:06

RoadRunner


Replace '==' with 'in'

"hello" in "123hello123"            # RETURNS True
"hello" in "aasdasdasd123hello123"  # RETURNS True
"hello" in "123123hello"            # RETURNS True
"hello" in "hello"                  # RETURNS True
like image 45
Rakesh Avatar answered Jun 16 '26 00:06

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!