Searching through list for words containing character
I am new to programming and am in an introductory course using python. I am trying to implement a function that takes a list of strings and a character as a parameter and prints to the screen, all the strings that have the given character in them. If the list is empty, the function returns 'List is empty'. So it should look like this:
Given:
wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')
Return:
Absolute Sense Test
Given:
wordsWithChar([],'r')
return:
'List is Empty'
EDIT: I have tried the following:
def wordsWithChar(lst,x):
for word in lst:
print(word,end=' ')
print()
if len(lst)<1:
print('List is empty')
def wordsWithChar(lst,x):
for word in lst:
print (word)
if x in word:
print(word)
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
newlst.append(word)
print(newlst)
if len(lst)<1:
print('List is empty')
if x in word:
newlst.append(x)
print(newlst)
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
if x in lst:
newlst.append(word)
return newlst
print(' ',join(lst))
newlst=wordsWithChar(lst,x)
if len(newlst)<1:
print('List is empty')
else:
print(newlst)
I have tried everything I know with for-loops and if/else statements and cannot figure this out. Thank you in advance for the help.
EDIT: While I appreciate all the help, with every solution presented, IDLE gets to the wordsWithChar test and just stops. It for some reason does not return any values. just skips to a new input line.
Solution 1:
You nearly nailed it:
def wordsWithChar(lst,x):
for word in lst:
print (word)
if x in word:
print(word)
The indentation of the if
statement makes it run after the loop. But you would want it to run inside the loop:
def wordsWithChar(lst,x):
for word in lst:
if x in word:
print(word)
if __name__ == "__main__":
wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')
This does not show the "not found" message. A more pythonic way would be to first create the list of words containing x using a list comprehension:
words_containing_x = [ w for w in lst if x in w ]
# words_containing_x = ['Absolute', 'Sense', 'Test']
Broken down:
-
words_containing_x =
- the new list -
[ w for w in lst ...]
the new list is allw
in the lists - a copy -
[... if x in w]
but only if the wordw
containsx
If this is a bit confusing, the the following will return the length
of all words in lst
that contain x
:
len_of_words_containing_x = [ len(w) for w in lst if x in w ]
# len_of_words_containing_x = [8, 5, 4]
Back to the question. The list can be tested:
def wordsWithChar(lst,x):
words_containing_x = [ w for w in lst if x in w ]
if words_containing_x:
print(words_containing_x)
else:
print("Oh noes!")