[英]search contains string in array python
我有一個類似於search = 'hello'
的字符串,我需要檢查所有數組以查看是否包含hello
。
例如:
"hello" == "123hello123" | true
"hello" == "aasdasdasd123hello123" | true
"hello" == "123123hello" | true
我需要搜索我的代碼
list_all_files_in_google_drive
- 它是我的所有文件名數組
filename
- 名稱文件,需要檢查是否存在於google驅動器中
if not any(file['title'] == filename for file in list_all_files_in_google_drive):
print('file not exist')
我的代碼不起作用,因為它的工作方式如下:
"hello" == "123hello123" | false
"hello" == "aasdasdasd123hello123" | false
"hello" == "123123hello" | false
"hello" == "hello" | true
我需要它像這樣工作:
"hello" == "123hello123" | true
"hello" == "aasdasdasd123hello123" | true
"hello" == "123123hello" | true
"hello" == "hello" | true
UPD:
我檢查了運營商in
和它不輸出true
filename = 'hello'
list = ['123hello123', 'aasdasdasd123hello123', '123123hello']
if filename in list:
print('true')
將'=='替換為'in'
"hello" in "123hello123" # RETURNS True
"hello" in "aasdasdasd123hello123" # RETURNS True
"hello" in "123123hello" # RETURNS True
"hello" in "hello" # RETURNS True
剛剛經歷與一個簡單的循環列表中的每個字符串,並檢查是否'hello'
與蟒蛇成員存在in
運營商:
lst = ['123hello123', 'aasdasdasd123hello123', '123123hello']
for x in lst:
if 'hello' in x:
print('true')
哪個輸出:
true
true
true
或者如果你想一次檢查all()
lst
中的字符串:
if all('hello' in x for x in lst):
print('true')
或者如果你想一次檢查lst
中是否有any()
字符串:
if any('hello' in x for x in lst):
print('true')
兩者都將輸出:
true
注意:在問題中顯示使用list
作為變量名稱不是一個好主意,因為它會影響內置函數list()
。 在這里返回一個布爾值True
或False
很好,不需要返回這些字符串形式。
試試這個家伙:
filename = 'hello'
list = ['123hello123', 'aasdasdasd123hello123', '123123hello']
if (filename.find(file) for file in list):
print('true')
您可以使用列表推導,如下所示:
filename = 'hello'
my_list = ['123hello123', 'aasdasdasd123hello123', '123123hello']
print all([True if filename in _ else False for _ in my_list])
filename = 'hello'
my_list = ['123hello123', 'aasdasdasd123hello123', '123123helo']
print all([True if filename in _ else False for _ in my_list])
輸出:
True
False
另一種解決方案是擁有如下自己的功能:
def check_filename(filename_string, input_list):
result = 'true'
for _ in input_list:
if filename_string not in _:
result = 'false'
break
return result
filename = 'hello'
my_list = ['123hello123', 'aasdasdasd123hello123', '123123hello']
print(check_filename(filename_string=filename, input_list=my_list))
filename = 'hello'
my_list = ['123hello123', 'aasdasdasd123ho123', '123123hello']
print(check_filename(filename_string=filename, input_list=my_list))
輸出:
true
false
'in'運算符是很好的解決方案,你也可以嘗試正則表達式:
import re
pattern=r'hello'
lst = ['123hello123', 'aasdasdasd123hello123', '123123hello','nothing']
for i in lst:
if re.search(pattern,i):
print("string : {} result : {} ".format(i,True))
else:
print("string : {} result : {} ".format(i,False))
輸出:
string : 123hello123 result : True
string : aasdasdasd123hello123 result : True
string : 123123hello result : True
string : nothing result : False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.