0

i am trying to check if str1 exist in str2

def string_contains(str1,str2):
    return bool (str1 in str2)

print (string_contains("llo","hello how are you"))
# expected false but return value is true
# the possible true for s1 is hello or hello how or hello how are
# hello how are you
user719852
  • 131
  • 1
  • 3
  • 8

2 Answers2

1

This should work - it will ensure only whole words are matched, and sentences must match from the start.

def string_contains(str1,str2):
    lst1 = str1.split(' ')
    lst2 = str2.split(' ')

    if len(lst1) <= len(lst2):
        return lst1 == lst2[:len(lst1)]

    return False

print (string_contains("llo", "hello how are you"))  # False
print (string_contains("hello", "hello how are you"))  # True
print (string_contains("hello how", "hello how are you"))  # True
print (string_contains("hello how a", "hello how are you"))  # False
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • You can use a `first_idx = lst2.index(lst1[0])` to get answers that don't match from the start. It can raise an exception that needs to be treated if there's no match between the list. – pekapa Jan 20 '16 at 02:15
0

I like using regular expression module re.

Code:

import re

pattern = re.compile('\sllo\s')  # add another parameter `re.I` for case insensitive
match = pattern.search('hello how are you')
if match:
    return True
else:
    return False
tanglong
  • 278
  • 2
  • 11