Reputation: 29
I need to find certain words in a list that have more than a certain amount of characters. I tried this but it just returns the original sentence as a list when it should be returning the strings with more than 5 characters.
def my_func(sentence):
answ = sentence.split()
for x in answ:
if len(x) >= 5:
return x
else:
return answ
Upvotes: 2
Views: 3182
Reputation: 178
def f(sentence):
return [i for i in sentence.split() if len(i) > 5]
s = "Hello, my name is Stephan"
print(f(s))
--->["Hello", "Stephan"]
This will return a list which contains each word that has more than 5 characters. The method that i used is called list comprehension.
Upvotes: 1
Reputation: 11228
you can use filter
function to filter out the value which is fulfilling the condition ie taking only those words which have more than equal to 5 characters
def func(sentence):
return list(filter(lambda word: len(word)>=5,sentence.split()))
Upvotes: -1
Reputation: 55
The code is just returning the word with size greater than 5 letters and if not found returning the sentence as List, which is not semantically correct.
The code below might solve your problem.
def my_func(sentence):
answ = sentence.split()
retList = []
for x in answ:
if len(x) >= 5:
retList.append(x)
return retList
Upvotes: 1
Reputation: 54
your if is returning on the else, remove the else and just return the if statement
Upvotes: 1