YUXUAN
YUXUAN

Reputation: 29

Need to find strings in a list with more than a certain amount of characters

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

Answers (4)

Emanuele
Emanuele

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

sahasrara62
sahasrara62

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

Siddhant Sukhatankar
Siddhant Sukhatankar

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

Richard Reed
Richard Reed

Reputation: 54

your if is returning on the else, remove the else and just return the if statement

Upvotes: 1

Related Questions