Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple strings exist in another string

How can I check if any of the strings in an array exists in another string?

Like:

a = ['a', 'b', 'c'] str = "a123" if a in str:   print "some of the strings found in str" else:   print "no strings found in str" 

That code doesn't work, it's just to show what I want to achieve.

like image 665
jahmax Avatar asked Aug 02 '10 16:08

jahmax


People also ask

How do you check if multiple strings exist in another string in Python?

You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any .

How do you check for multiple substrings in a string?

Using regular expressions, we can easily check multiple substrings in a single-line statement. We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.

How do you check if a string is in another string Python?

Using find() to check if a string contains another substring We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

How do I check if a string contains more than one character in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .


1 Answers

You can use any:

a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"]  if any(x in a_string for x in matches): 

Similarly to check if all the strings from the list are found, use all instead of any.

like image 115
Mark Byers Avatar answered Oct 13 '22 14:10

Mark Byers