Python | Check if substring is part of List of Strings

Many problems of substrings have been dealt with many times. There can also be such problem in which we require to check if argument string is a part of any of the strings coming in the input list of strings. Let’s discuss various ways in which this can be performed.

Method #1 : Using join()
The basic approach that can be employed to perform this particular task is computing the join of all the list strings and then searching the string in the joined string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if substring is part of List of Strings
# Using join()
  
# initializing list  
test_list = ['GeeksforGeeks', 'is', 'Best']
  
# test string 
check_str = "for"
  
# printing original string 
print("The original string is : " + str(test_list))
  
# Using join()
# Check if substring is part of List of Strings
temp = '\t'.join(test_list)
res = check_str in temp
  
# printing result 
print("Is check string part of any input list string : " + str(res))

chevron_right


Output :



The original string is : ['GeeksforGeeks', 'is', 'Best']
Is check string part of any input list string : True

 

Method #2 : Using any()
The any function can be used to compute the presence of the test substring in all the strings of the list and return True if it’s found in any. This is better than above function as it doesn’t explicitly take space to create new concatenated string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if substring is part of List of Strings
# Using any()
  
# initializing list  
test_list = ['GeeksforGeeks', 'is', 'Best']
  
# test string 
check_str = "for"
  
# printing original string 
print("The original string is : " + str(test_list))
  
# Using any()
# Check if substring is part of List of Strings
res = any(check_str in sub for sub in test_list)
  
# printing result 
print("Is check string part of any input list string : " + str(res))

chevron_right


Output :

The original string is : ['GeeksforGeeks', 'is', 'Best']
Is check string part of any input list string : True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.