def checkIt(arr,inp):
	bool = 0
	for i in arr:
		if i in inp:
			bool = 1
			break
	return bool

array = ['hi','hey','hello']
string = "Hi there!"

if checkIt(array,string)
	print "Yay!";

That's my code. It returns, "Yay!". Now... I like what it does-- it searches the string for a value in an array, and if it finds it, returns true. However, if the string were "What a high mountain!", it would still return true. As you can see, in "high", the characters 'hi' can be found. I'd like it to search for a whole word, rather than a couple characters. How could I do this? Thanks!

You could add inp = list(inp) as the first line in your function.
Also you should avoid using names like 'bool', 'array' or 'string' (type or module names) as variable names :)

Thanks for your response--- I'll try it later.

What does list() do?

sorry, I meant inp.split() . The reason is that

"hi" in ["What", "a", "high", "mountain"]

is False !

That works, but what if a value in the array is more than one word?

There is a solution with the re module. You can build a regular expression by joining all the elements of array

array = ["hi", "hey there", "Hello world"]
myPattern = re.compile("|".join([re.escape(w) for w in array]))
checkIt = myPattern.search

if checkIt("foo bar buzz hey there, what are you doing?"):
  print "Yay!"

However, I'm not sure its so efficient if the array is large. For example, if the elements of the array are sequences of words separated by white space, it could be better to look for all words and blocks of white space in the string...

What changes should I make to my function? You aren't very clear as to where..

def checkIt(arr,inp):
	inp = input.split(' ')
	bool = 0
	for i in arr:
		if i in inp:
			bool = 1
			break
	return bool

If you don't fully understand the re module (I don't), you could always have it look for the first word in that two-word value (in the array), and then if it found the first one, see if the word following it in the input is the same as the second word in the two-word value. Sorry if I didn't make that very clear. But anyways, I think that Gribouillis' idea would be the best, as it's straight-forward and clean looking.

If I merge array values into one array.. value.. what is the point of my function?

Let me get one thing straight: Are any of the array values ever going to be more than one word long? Because earlier in this thread you asked how to deal with it in that situation...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.